PHP数组是一种非常强大的数据结构,用于存储多个值。数组在PHP中非常灵活,可以用于各种场景。以下是PHP数组的一些常见用法:
php
$fruits = array("Apple", "Banana", "Cherry");
// 或者
$fruits = ["Apple", "Banana", "Cherry"];
php
$person = array("name" => "John", "age" => 30, "city" => "New York");
// 或者
$person = ["name" => "John", "age" => 30, "city" => "New York"];
php
echo $fruits[0]; // 输出: Apple
echo $person["name"]; // 输出: John
使用foreach
循环遍历数组。
```php
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
foreach ($person as $key => $value) { echo "$key: $value\n"; } ```
php
$fruits[] = "Orange";
php
$person["email"] = "john@example.com";
unset()
函数删除数组元素。
php
unset($fruits[1]); // 删除 "Banana"
unset($person["age"]); // 删除 "age" 键及其值
php
echo count($fruits); // 输出: 3
php
array_push($fruits, "Orange", "Mango");
php
$lastFruit = array_pop($fruits);
php
$moreFruits = ["Grapes", "Pineapple"];
$allFruits = array_merge($fruits, $moreFruits);
php
$keys = array_keys($person);
php
$values = array_values($person);
php
if (in_array("Apple", $fruits)) {
echo "Apple is in the array!";
}
php
$key = array_search("Banana", $fruits);
echo $key; // 输出: 1
php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[1][2]; // 输出: 6
php
sort($fruits);
php
rsort($fruits);
php
asort($person);
php
ksort($person);
php
$numbers = [1, 2, 3, 4, 5];
$evenNumbers = array_filter($numbers, function($value) {
return $value % 2 == 0;
});
php
$numbers = [1, 2, 3];
$squaredNumbers = array_map(function($value) {
return $value * $value;
}, $numbers);
php
$slice = array_slice($fruits, 1, 2); // 从索引1开始,取2个元素
php
$reversedFruits = array_reverse($fruits);
php
$uniqueFruits = array_unique($fruits);
php
$fruitString = implode(", ", $fruits);
php
$fruitsArray = explode(", ", $fruitString);
php
$serialized = serialize($fruits);
php
$unserialized = unserialize($serialized);
php
$json = json_encode($fruits);
php
$array = json_decode($json, true);
php
$flipped = array_flip($fruits);
php
$randomKey = array_rand($fruits);
php
$filledArray = array_fill(0, 5, "Hello");
php
$diff = array_diff($fruits, ["Banana", "Cherry"]);
php
$intersect = array_intersect($fruits, ["Apple", "Banana"]);
php
if (array_key_exists("name", $person)) {
echo "Name exists!";
}
php
array_walk($fruits, function(&$value, $key) {
$value = strtoupper($value);
});
php
$keys = ["a", "b", "c"];
$values = [1, 2, 3];
$combined = array_combine($keys, $values);
php
$replaced = array_replace($fruits, [1 => "Blueberry"]);
php
$sum = array_sum([1, 2, 3, 4, 5]); // 输出: 15
php
$product = array_product([1, 2, 3, 4, 5]); // 输出: 120
php
$flipped = array_flip($fruits);
php
shuffle($fruits);
php
uasort($person, function($a, $b) {
return $a <=> $b;
});
php
$filtered = array_filter($person, function($value) {
return $value > 25;
});
PHP数组功能非常丰富,几乎可以满足所有数据处理的需求。掌握这些数组操作技巧,可以大大提高开发效率。