PHP array()函数
定义和用法
array() 函数用于创建PHP数组。此函数可用于创建索引数组或关联数组。PHP数组可以是单维的或多维的。
语法
创建PHP索引数组的语法:
$a = array(value1, value2, value3, ...)
创建PHP关联数组的语法:
$a = array(key1 => value1, key2 => value2...)
参数
序号 | 参数与描述 |
---|---|
1 | 键(可选) 指定键的类型为数字或字符串。如果未设置,则会生成一个以0开始的整数键 |
2 | 值(必需) 指定值 |
返回值
这个函数返回一个参数数组。
PHP版本
这个函数是作为核心PHP 4.0.0的一部分首次引入的。
示例
以下示例创建一个空的PHP数组:
<?php
abc = array();
print_r(abc);
?>
这将产生以下结果:
Array ()
示例
以下示例创建一个带有几个元素的PHP索引数组:
<?php
abc = array("A", "B", "C");
print_r(abc);
?>
这将产生以下结果−
Array
(
[0] => A
[1] => B
[2] => C
)
示例
下面的示例创建了一个带有数字作为键的PHP关联数组:
<?php
abc = array(1 => "One", 2 => "Two", 3 => "Three");
print_r(abc);
?>
这将产生以下结果:
Array
(
[1] => One
[2] => Two
[3] => Three
)
示例
下面的示例创建一个带有字符串键的PHP关联数组:
<?php
abc = array("one" => "One", "two" => "Two", "three" => "Three");
print_r(abc);
?>
这将产生以下结果 −
Array
(
[one] => One
[two] => Two
[three] => Three
)
示例
以下示例展示了如何在现有PHP数组中添加更多的值:
<?php
abc = array(1 => "One", 2 => "Two", 3 => "Three");
print_r(abc);
/* Add two more value in above array */
abc[4] = "Four";abc[5] = "Five";
print_r($abc);
?>
这将产生以下结果−
Array
(
[1] => One
[2] => Two
[3] => Three
)
Array
(
[1] => One
[2] => Two
[3] => Three
[4] => Four
[5] => Five
)
示例
以下示例演示了如何创建二维数组,如何为关联数组指定键,以及如何在普通数组中跳过并继续数字索引。
<?php
fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
print_r(fruits);
?>
这将产生以下结果 –
Array
(
[fruits] => Array
(
[a] => orange
[b] => banana
[c] => apple
)
[numbers] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
[holes] => Array
(
[0] => first
[5] => second
[6] => third
)
)
示例
要删除单个数组元素或完整数组,可以使用 unset() 函数:
<?php
abc = array(1 => "One", 2 => "Two", 3 => "Three");
print_r(abc);
/* Now let's delete element with index 2*/
unset( abc[2] );
print_r(abc);
/* Now let's delete complete array */
unset(abc);
print_r(abc);
?>
这将产生以下结果 –
Array
(
[1] => One
[2] => Two
[3] => Three
)
Array
(
[1] => One
[3] => Three
)
PHP Notice: Undefined variable: abc in main.php on line 13