array()函数是用来创建一个PHP数组。该函数可用于创建索引数组或关联数组。PHP数组可以是一维或多维的。
创建PHP索引数组的语法:
$a = array(value1, value2, value3, ...)
创建PHP关联数组的语法:
$a = array(key1 => value1, key2 => value2...)
序号 | 参数及说明 |
---|---|
1 | key(可选) 它指定数字或字符串类型的键。如果未设置,则生成一个整数键,从0开始 |
2 | value(必填) 它指定值 |
此函数返回参数数组。
此函数最初是作为核心PHP 4.0.0的一部分引入的。
下面的示例创建一个包含少量元素的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); /*在上面的数组中再加两个值 */ $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); /* 现在让我们删除索引为2的元素*/ unset( $abc[2] ); print_r($abc); /* 现在让我们删除整个数组 */ 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