Can't concatenate 2 arrays in PHP
✔ Recommended Answer
Both will have a key of 0
, and that method of combining the arrays will collapse duplicates. Try using array_merge()
instead.
$arr1 = array('foo'); // Same as array(0 => 'foo')$arr2 = array('bar'); // Same as array(0 => 'bar')// Will contain array('foo', 'bar');$combined = array_merge($arr1, $arr2);
If the elements in your array used different keys, the +
operator would be more appropriate.
$arr1 = array('one' => 'foo');$arr2 = array('two' => 'bar');// Will contain array('one' => 'foo', 'two' => 'bar');$combined = $arr1 + $arr2;
Source: stackoverflow.com
Answered By: awgy
You can concatenate two arrays in PHP using the array_merge()
function. Here's an example:
php<?php
// define two arrays
$array1 = ['apple', 'banana', 'orange'];
$array2 = ['grape', 'kiwi', 'pineapple'];
// concatenate the arrays using array_merge()
$concatenated_array = array_merge($array1, $array2);
// print the concatenated array
print_r($concatenated_array);
?>
In this example, we define two arrays $array1
and $array2
. We then concatenate the arrays using array_merge()
, which returns a new array that contains all the elements from both arrays. Finally, we print the concatenated array using print_r()
. The output should be:
csharpArray
(
[0] => apple
[1] => banana
[2] => orange
[3] => grape
[4] => kiwi
[5] => pineapple
)
If you want to preserve the keys of the original arrays, you can use the +
operator to merge the arrays instead:
php<?php
// define two arrays
$array1 = ['a' => 'apple', 'b' => 'banana', 'o' => 'orange'];
$array2 = ['g' => 'grape', 'k' => 'kiwi', 'p' => 'pineapple'];
// concatenate the arrays using the + operator
$concatenated_array = $array1 + $array2;
// print the concatenated array
print_r($concatenated_array);
?>
In this example, we use the +
operator to concatenate the arrays while preserving the keys. The output should be:
csharpArray
(
[a] => apple
[b] => banana
[o] => orange
[g] => grape
[k] => kiwi
[p] => pineapple
)
Comments
Post a Comment