-2

I have two arrays from the database, one with all first names and one with all last names. I want to do the following:

First name array

0 => john
1 => jane
enter code here

Last name array

0 => doe
1 => joe

I want to add these two arrays together, in a way that the first name of the array key matches the last name of the same array key. For example, when I add these two together the outcome should be

0 => john doe
1 => jane joe

Any help?

Silvan
  • 5
  • 2
  • 3
    _“Any help?”_ - any _attempt_? Loop over one, and use the current index to access the corresponding item in the other. Perform string concatenation, assign result to a new item in result array. – CBroe Jun 17 '21 at 13:45
  • Take a look at [Is there a php function like python's zip?](https://stackoverflow.com/q/2815162/3744182). – dbc Jun 17 '21 at 18:40

1 Answers1

0

Since both the arrays should be combined on the same index, we can use a simple for loop and use that index to get both the values;

<?php

$first = [ 'john', 'jane' ];
$last  = [ 'doe', 'joe' ];
$res   = [];

for ($i = 0; $i < sizeof($first); $i++) {
    $res[] = "{$first[$i]} {$last[$i]}";
}

var_dump($res);

Will produce:

array(2) {
  [0]=>
  string(8) "john doe"
  [1]=>
  string(8) "jane joe"
}
Try it online!
0stone0
  • 21,605
  • 3
  • 29
  • 49