PHP - array_replace
Trieda
Metóda - array_replace
(PHP 5 >= 5.3.0, PHP 7)
The function replaces the values from the first array with the values from the following arrays.
- If a key from the first array (array 1) exists also in the following array (array 2), the value from the first array will be replaced by the value from the array 2.
- If a key exists only in the first array, the key and a value will be left as they are.
- If a key exists in the array 2 and does not exists in the first array (array 1), it'll be created in the first array.
Note: The function is not recursive, if we need to replace
in multidimensional arrays, we can use the
array_replace_recursive() function.
Procedurálne
- function array_replace (array $array1, array $array2, array $...) : array
Parametre
| Názov | Dátový typ | Predvolená hodnota | Popis |
|---|---|---|---|
| $array1 | array | The array which values will be replaced. | |
| $array2 | array | The array which values will replace the values in the first array. Only values with the same key will be replaced. If the key does not exist in the first array, it will be created. | |
| $... | array | We can pass more arrays for which applies the same as for the second parameter. Values from the later arrays will overwrite the previous ones. |
Mávratovej hodnoty
Vracia: array
Returns an array with replaced values. If an error occurs, returns NULL.
Príklady
The first example: two associative arrays with different values.
<?php
$array1 = array("firstName" => "John", "lastName" => "Rambo", "age" => 30);
$array2 = array("firstName" => "Chuck", "lastName" => "Norris", "bestMovie" => "Lone Wolf McQuade");
print_r(array_replace($array1, $array2));
echo "<br>";
// Adding the third array.
$array3 = array("firstName" => "Rocky", "lastName" => "Balboa", "age" => 40, "bestMovie" => "Rocky 1");
print_r(array_replace($array1, $array2, $array3));
The second example: three indexed arrays with different values.
<?php
$usaCars = array("Ford", "Cadillac");
$germanCars = array("BMW", "Mercedes", "Audi", "VW");
$japaneseCars = array("Toyota", "Mazda", "Honda", "Subaru");
print_r(array_replace($usaCars, $germanCars, $japaneseCars));
echo "<br>";
// We add some numeric keys and the result is different.
$usaCars = array("Ford", 8 => "Cadillac");
$germanCars = array("BMW", "Mercedes", 5 => "Audi","VW");
$japaneseCars = array("Toyota", "Mazda", "Honda", "Subaru");
print_r(array_replace($usaCars, $germanCars, $japaneseCars));
Súvisiace manuály
- function array_merge (array $array1, array $...) : array
