php中array_unshift()修改数组key注意事项分析

本文实例分析了php中array_unshift()修改数组key注意事项。分享给大家供大家参考,具体如下:

众所周知,array_unshift()用来在数组的开头添加元素,但今天突然发现如果数组的键值是数字类型的(或能转成数字类型的),array_unshift()会修改所有键为数字的元素的Key,真是坑啊

实例:

  1. $a=array(111=>"dddddddddddd","112"=>array("one"=>"orange","two"=>"hhhhh"), "113"=>array("one"=>"orange","two"=>"hhhhh"),"oooo"=>"jjjjj");
  2. print_r($a);echo "</br>";
  3. array_unshift($a, "aaaaaaaaa");
  4. print_r($a);echo "</br>";

输出结果:

  1. Array ( [111] => dddddddddddd [112] => Array ( [one] => orange [two] => hhhhh ) [113] => Array ( [one] => orange [two] => hhhhh ) [oooo] => jjjjj )
  2. Array ( [0] => aaaaaaaaa [1] => dddddddddddd [2] => Array ( [one] => orange [two] => hhhhh ) [3] => Array ( [one] => orange [two] => hhhhh ) [oooo] => jjjjj )

看到了吧,array_unshift()后数组键值发生了变化,原来的111变成了1,真是坑哪!以后大家在使用array_unshift()的时候对此需要格外注意了!