PHP 阵列(数组)合并、增加元素、插入指定位置

1.合并 note: call by value.


$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

2.增加 note: call by reference.


$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

3.插入指定位置 note: call by reference.


$array1 = array('a', 'b', 'c', 'd', 'e');
$array2 = array('x');
array_splice($array1, 3, 0, $array2); // 插入到位置3且删除0个
print_r($array1);
?>

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => x
    [4] => d
    [5] => e
)

你可能感兴趣的:(PHP)