Ben Marshall
Ben Marshall

Reputation: 1764

How to combine two PHP arrays while ignoring keys

Thought this was an easy one, but after Googling around for awhile, I've come up short. I need to combine two PHP arrays while ignoring the keys:

array(
  0 => 'Word 1',
  1 => 'Word 2'
)

array(
  0 => 'Word 3',
  1 => 'Word 4',
  2 => 'Word 5'
)

Result should be:

array(
  0 => 'Word 1',
  1 => 'Word 2',
  2 => 'Word 3',
  3 => 'Word 4',
  4 => 'Word 5'
)

Tried array_merge but that replaces duplicate keys. array_combine won't work because it requires the same numer of elements in both array.

Upvotes: 4

Views: 5542

Answers (3)

Roman Samarsky
Roman Samarsky

Reputation: 390

Since PHP 7.4 it's also possible with ... operator.

$arr1 = ['a', 'b', 'c'];
$arr2 = ['d', 'e', 'f'];

return [...$arr1,  ...$arr2]; // ['a', 'b', 'c', 'd', 'e', 'f']

Upvotes: 9

Lionel Chan
Lionel Chan

Reputation: 8059

array_merge should do the trick. If it doesn't, meaning your keys are probably not numeric. Try converting them into plain values based arrays first, then merge them.

array_merge(array_values($a), array_values($b))

Should do the trick.

Sample: https://3v4l.org/chuXV

array_values: http://php.net/manual/en/function.array-values.php

Upvotes: 23

Wojo
Wojo

Reputation: 65

//Try using two for loops to copy the data over to a third array like this.   
<?php
       $a1 = array(
         0 => 'w1', 
         1 => 'w2'
       );
       $a2 = array(
         0 => 'w3', 
         1 => 'w4', 
         2 => 'w5'
       );



      $counter = 0;

      for($i = 0; $i < count($a1); $i++){
        $a3[$counter] = $a1[$i];
        $counter++;
      }
      for($i = 0; $i < count($a2); $i++){
        $a3[$counter] = $a2[$i];
        $counter++;
      }
      print_r($a3);
?>

Upvotes: -2

Related Questions