0

Very simplified example:

function returnArray() {
  return array('First','Second','Third');
}

$arr = array('hello','world');
$arr[] = returnArray();
print_r($arr);

I was (wrongly) expecting to see $arr containing 5 elements, but it actually contains this (and I understand it makes sense):

Array
(
    [0] => hello
    [1] => world
    [2] => Array
        (
            [0] => First
            [1] => Second
            [2] => Third
        )

)

Easily enough, I "fixed" it using a temporary array, scanning through its elements, and adding the elements one by one to the $arr array.

But I guess/hope that there must be a way to tell PHP to add the elements automatically one by one, instead of creating a "child" array within the first one, right? Thanks!

2 Answers 2

3

You can use array_merge,

$arr = array_merge($arr, returnArray());

will result in

Array
(
    [0] => hello
    [1] => world
    [2] => First
    [3] => Second
    [4] => Third
)

This will work smoothly here, since your arrays both have numeric keys. If the keys were strings, you’d had to be more careful (resp. decide if that would be the result you want, or not), because

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

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

Comments

0

You are appending the resulting array to previously created array. Instead of the use array merge.

function returnArray() {
  return array('First','Second','Third');
}

$arr = array('hello','world');
$arr = array_merge($arr, returnArray());
print_r($arr);

Comments

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.