質問

Is it possible to concatenate an array using inline code (i.e. inside the array declaration)? For instance:

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

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

var_dump($arr);

will result in:

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

Whereas the desired result would be:

Array(
    [one] => 1
    [two] => 2
    [three] => 3
    [four] => 4
    [five] => 5
)
役に立ちましたか?

解決

Use array_merge(). It is an extra step but since you can't do this during the array declaration it is the next best thing.

$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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top