1

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
)

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but is it possible to do so within the initial array declaration?
@YoavKadosh: No it is not. You could also try the "array union" (+) operator: $array = array('one' => 1, 'two' => 2) + array('three' => 3);
Ok, that's what I wanted to know.
@RocketHazmat that's exactly what I was looking for. If you want, you can post that as an answer and i'll accept it (sorry John... :) ).
@YoavKadosh: That's the same thing as array_merge except it has a different behavior when it comes to duplicate keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.