CY-Left

PHP开发语言

PHP 细节知识

PHP 细节

(一) 数组合并

$a = [
    'a0',
    'b0',
    'c0',
    'a' => 'a'
];
$b = [
    'a1',
    'b1',
    'c1',
    'a'=>'b'
];
  1. $a+$b;
    > 相同索引相同键的值会被 $a (前者)覆盖, 不同键保留.
array(4) {
  [0] => string(2) "a1"
  [1] => string(2) "b1"
  [2] => string(2) "c1"
  ["a"] => string(1) "b"
}
  1. array_merage($a, $b);
    > 相同键被覆盖, 相同索引不会被前者覆盖
array(7) {
  [0] => string(2) "a0"
  [1] => string(2) "b0"
  [2] => string(2) "c0"
  ["a"] => string(1) "b"
  [3] => string(2) "a1"
  [4] => string(2) "b1"
  [5] => string(2) "c1"
}

(二) foreach

$a = [
    'a0',
    'b0',
    'c0',
    'a' => 'a'
];
foreach($a as $k=>$v){
    $v = 1;
}
foreach($a as $v){
    echo $v;
}

foreach 仅仅处理数组的副本, 故修改不会改变原数组.

a0b0c0a

另外 each 已经被弃用了.

本文虽拙,却也系作者劳动,转载还请保留本文链接: http://cyleft.com/?p=770