Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP array_merge function

The PHP array_merge function combines 2 or more arrays, resulting in a new array.

Description / Descripción
 array_merge(array ...$arrays): array
Sintaxis / Sintax
$merged_array = array_merge($array1, array2);
$merged_array2 = array_merge($array1, array2,array3);

Cases

Asociative arrays

If the arrays have the same keys, the value will be overwritten. For example, if I have 2 arrays:

$A =["name"=>"Pancho", "raza"=>"caniche"] y $B =["name"=>"Rocko", "peso"=>"20kg"] if $C my combined array $C would be $C=["name"=>"Rocko","raza"=>"caniche", "peso"=>"20kg"]

When we see an image like this, what we are seeing are the keys; if the keys are the same, it will take the value from the last array.

Numeric and Indexed Arrays

In this case, the combination has a different behavior. In these cases, the values that have the same index will not be overwritten but will be added to the new array that starts from 0.

if we have 2 arrays: $A=["toyota","mazda"] and $B=["ford","chevrolet"] these 2 arrays have indices 0 and 1, the combination that we get when we apply the array_merge function will be $C=["toyota","mazda","ford","chevrolet"]

Parameters

…$arrays – these are the arrays that will be combined, the idea is that you pass at least 2 arrays

Returns

array – is the result of the combination

Array without anything – in case of calling array_merge without parameters

PHP array_merge examples

The first example we will see is one with indexed arrays, notice how the array_merge function treats these arrays.

$array1 = array('Toyota', 'Honda', 'Ford');
$array2 = array('Chevrolet', 'Nissan', 'BMW');

$mergedArray = array_merge($array1, $array2);

print_r($mergedArray);
Array
(
    [0] => Toyota
    [1] => Honda
    [2] => Ford
    [3] => Chevrolet
    [4] => Nissan
    [5] => BMW
)

In this other example, we see how the array_merge function treats associative arrays. Maybe you want to change the value of Japan to another country in the second array to see more clearly how it combines the arrays.

$array1 = array('Toyota' => 'Japón', 'Ford' => 'Estados Unidos');
$array2 = array('Toyota' => 'Japón', 'Chevrolet' => 'Estados Unidos');

$mergedArray = $array1 + $array2;

print_r($mergedArray);
Array
(
    [Toyota] => Japón
    [Ford] => Estados Unidos
    [Chevrolet] => Estados Unidos
)

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category