内联数组连接?

时间:2014-03-10 19:22:03

标签: php arrays concatenation inline

是否可以使用内联代码(即在数组声明中)连接数组? 例如:

function get_array() {
    return array('four' => 4, 'five' => 5);
}

$arr = array(
    'one' => 1,
    'two' => 2,
    'three' => 3,
    get_array()
);

var_dump($arr);

将导致:

Array(
    [one] => 1
    [two] => 2
    [three] => 3
    [0] => Array(
        [four] => 4
        [five] => 5
    )
)

期望的结果是:

Array(
    [one] => 1
    [two] => 2
    [three] => 3
    [four] => 4
    [five] => 5
)

1 个答案:

答案 0 :(得分:6)

使用array_merge()。这是一个额外的步骤,但由于你不能在数组声明中这样做,这是下一个最好的事情。

$new_array = array_merge($arr, array('four' => 4, 'five' => 5));

print_r($new_array);
Array ( [one] => 1 [two] => 2 [three] => 3 [four] => 4 [five] => 5 )

See it in action