array()函數(shù)是用來創(chuàng)建一個(gè)PHP數(shù)組。該函數(shù)可用于創(chuàng)建索引數(shù)組或關(guān)聯(lián)數(shù)組。PHP數(shù)組可以是一維或多維的。
創(chuàng)建PHP索引數(shù)組的語法:
$a = array(value1, value2, value3, ...)
創(chuàng)建PHP關(guān)聯(lián)數(shù)組的語法:
$a = array(key1 => value1, key2 => value2...)
序號(hào) | 參數(shù)及說明 |
---|---|
1 | key(可選) 它指定數(shù)字或字符串類型的鍵。如果未設(shè)置,則生成一個(gè)整數(shù)鍵,從0開始 |
2 | value(必填) 它指定值 |
此函數(shù)返回參數(shù)數(shù)組。
此函數(shù)最初是作為核心PHP 4.0.0的一部分引入的。
下面的示例創(chuàng)建一個(gè)空的PHP數(shù)組:
<?php $abc = array(); print_r($abc); ?>測(cè)試看看?/?
輸出結(jié)果
Array ()
下面的示例創(chuàng)建一個(gè)包含少量元素的PHP索引數(shù)組:
<?php $abc = array("A", "B", "C"); print_r($abc); ?>測(cè)試看看?/?
輸出結(jié)果
Array ( [0] => A [1] => B [2] => C )
以下示例創(chuàng)建一個(gè)以數(shù)字為鍵的PHP關(guān)聯(lián)數(shù)組:
<?php $abc = array(1 => "One", 2 => "Two", 3 => "Three"); print_r($abc); ?>測(cè)試看看?/?
輸出結(jié)果
Array ( [1] => One [2] => Two [3] => Three )
以下示例創(chuàng)建一個(gè)以字符串為鍵的PHP關(guān)聯(lián)數(shù)組:
<?php $abc = array("one" => "One", "two" => "Two", "three" => "Three"); print_r($abc); ?>測(cè)試看看?/?
輸出結(jié)果
Array ( [one] => One [two] => Two [three] => Three )
以下示例說明如何在現(xiàn)有的PHP數(shù)組中添加更多值:
<?php $abc = array(1 => "One", 2 => "Two", 3 => "Three"); print_r($abc); /*在上面的數(shù)組中再加兩個(gè)值 */ $abc[4] = "Four"; $abc[5] = "Five"; print_r($abc); ?>測(cè)試看看?/?
輸出結(jié)果
Array ( [1] => One [2] => Two [3] => Three ) Array ( [1] => One [2] => Two [3] => Three [4] => Four [5] => Five )
下面的示例演示如何創(chuàng)建二維數(shù)組,如何為關(guān)聯(lián)數(shù)組指定鍵以及如何在普通數(shù)組中跳過并繼續(xù)數(shù)字索引。
<?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); ?>測(cè)試看看?/?
輸出結(jié)果
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 ) )
要?jiǎng)h除單個(gè)數(shù)組元素或完整數(shù)組,可以使用unset()函數(shù):
<?php $abc = array(1 => "One", 2 => "Two", 3 => "Three"); print_r($abc); /* 現(xiàn)在讓我們刪除索引為2的元素*/ unset( $abc[2] ); print_r($abc); /* 現(xiàn)在讓我們刪除整個(gè)數(shù)組 */ unset($abc); print_r($abc); ?>測(cè)試看看?/?
輸出結(jié)果
Array ( [1] => One [2] => Two [3] => Three ) Array ( [1] => One [3] => Three ) PHP Notice: Undefined variable: abc in main.php on line 13