2

I have three arrays right now the values of which I want to combine together. All of the values have matching keys but I can't work out quite how to do it. To put it more visually I have:

array{
    [0] => "Foo"
}

array{
    [0] => " Bar"
}

and I want:

array{
    [0] => "Foo Bar"
}

But for the life of me I can't figure out how! At first I thought about using nested foreach statements like

$result = array();

foreach ($array1 as &$input1) {
    foreach ($array2 as &$input2) {
        $result[] = $input1 . $input2;
    }
}

But while that combined the values, it generated a lot of correct ones (The array was about twice the size as expected).

1
  • 2
    Note there is no need to use & for loop variables if you are not going to modify it. Commented Jul 2, 2015 at 15:08

1 Answer 1

3

Use the keys

$output = array();

foreach (array_keys($array1) as $key) {
    $output[] = $array1[$key] . $array2[$key]; // and possibly . $array3[$key]
}
Sign up to request clarification or add additional context in comments.

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.