PHP 数组

数组可以在单个(数组)变量中存储多个(不同类型的)值,并且可以根据 键(key) 访问其中的 值(value)。

https://www.php.net/manual/zh/language.types.array.php

数值数组

					
<?php
  //自动分配 ID 键(ID 键总是从 0 开始):
  $names = array("wanghao", "xiaoming", "lili");
  var_dump($names);
  var_dump($names[0]);

  //手动分配 ID 键:
  $ages[0] = 18;
  $ages[1] = 20;
  $ages[3] = 21;
  var_dump($ages);

  //一个数组变量中可以存储不同类型的值
  $wanghao = array("wanghao", 18, true);
  var_dump($wanghao);

 ?>
					
				

PHP 5.5.12 版本输出:

					
array (size=3)
  0 => string 'wanghao' (length=7)
  1 => string 'xiaoming' (length=8)
  2 => string 'lili' (length=4)

string 'wanghao' (length=7)

array (size=3)
  0 => int 18
  1 => int 20
  3 => int 21

array (size=3)
  0 => string 'wanghao' (length=7)
  1 => int 18
  2 => boolean true
					
				

PHP 5.6.40 版本输出:

					
array(3) {
  [0]=>
  string(7) "wanghao"
  [1]=>
  string(8) "xiaoming"
  [2]=>
  string(4) "lili"
}
string(7) "wanghao"
array(3) {
  [0]=>
  int(18)
  [1]=>
  int(20)
  [3]=>
  int(21)
}
array(3) {
  [0]=>
  string(7) "wanghao"
  [1]=>
  int(18)
  [2]=>
  bool(true)
}
					
				

关联数组

以 key=>value 键值对形式存在的数组。

					
<?php
  $people = array("wanghao"=>18, "xiaoming"=>20, "lili"=>21);
  var_dump($people);
  var_dump($people[0]);    //无效 index/offset
  var_dump($people['wanghao']);

  $address['wanghao'] = "beijing";
  $address['xiaoming'] = "shanghai";
  $address['lili'] = "wuhan";
  var_dump($address);

  $num = array('0'=>"wanghao", '1'=>"xiaoming", '2'=>"lili");
  var_dump($num);
  var_dump($num[0]);       //有效
  var_dump($num['0']);     //有效
 ?>
					
				

输出:

					
array (size=3)
  'wanghao' => int 18
  'xiaoming' => int 20
  'lili' => int 21

Notice: Undefined offset: 0 in XXX
null

int 18

array (size=3)
  'wanghao' => string 'beijing' (length=7)
  'xiaoming' => string 'shanghai' (length=8)
  'lili' => string 'wuhan' (length=5)

array (size=3)
  0 => string 'wanghao' (length=7)
  1 => string 'xiaoming' (length=8)
  2 => string 'lili' (length=4)

string 'wanghao' (length=7)

string 'wanghao' (length=7)