- PHP array_replace() Function
- Example 1: How to replace values in the PHP array
- Example 2: If the key exists in array2 and not in array1
- Example 3: Using three arrays in PHP array_replace()
- Example 4: Using numeric keys
- array_replace
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 15 notes
- PHP array_replace() Function
- Definition and Usage
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example 1
- Example 2
- Example 3
- Example 4
PHP array_replace() Function
It returns the replaced array. If any error occurs during function execution, it returns NULL.
Example 1: How to replace values in the PHP array
$brandsA = [ 'a' => 'Louis Vuitton', 'b' => 'Hermès', 'c' => 'Gucci', 'd' => 'Prada', 'e' => 'Chanel', 'f' => 'Cartier' ]; $brandsB = [ 'b' => 'Tesla', 'd' => 'Coca-cola', 'e' => 'Google', 'f' => 'Facebook' ]; $replaced = array_replace($brandsA, $brandsB); print_r($replaced);
In the code, we have defined two arrays. Now, we are replacing some of the items of brandsA with brandsB. If the keys of a brandsA match with the brandsB, it will replace the values of the brandsA with the brandsB. See the below output.
Example 2: If the key exists in array2 and not in array1
Let’s see the scenario where the key exists in array1, not in array2, and use the array_replace() function.
$brandsA = [ 'a' => 'Louis Vuitton', 'b' => 'Hermès', 'c' => 'Gucci', 'd' => 'Prada', 'e' => 'Chanel', 'f' => 'Cartier' ]; $brandsB = [ 'x' => 'Tesla', 'y' => 'Coca-cola', 'z' => 'Google', 'w' => 'Facebook' ]; $replaced = array_replace($brandsA, $brandsB); print_r($replaced);
In the above code, both brandsA and brandsB have different keys. That is why when we use the array_replace() function, it will output from both arrays combined. So, the output is the following.
Example 3: Using three arrays in PHP array_replace()
If we use three arrays, the last array($array3) the last array will overwrite the previous ones ($a1 and $a2).
$brandsA = [ 'a' => 'Louis Vuitton', 'b' => 'Hermès', 'c' => 'Gucci', 'd' => 'Prada', 'e' => 'Chanel', 'f' => 'Cartier' ]; $brandsB = [ 'x' => 'Tesla', 'y' => 'Coca-cola', 'z' => 'Google', 'w' => 'Facebook' ]; $brandsC = [ 'a' => 'Rolex', 'b' => 'Zara', 'y' => 'Pepsico', 'z' => 'Alibaba', ]; $replaced = array_replace($brandsA, $brandsB, $brandsC); print_r($replaced);
Example 4: Using numeric keys
If a key exists in arrA and not in arrB.
$arrA = ['disney', 'netflix', 'hulu']; $arrB = [0 => 'sports', 1 => 'games', 2 => 'discovery']; $replaced = array_replace($arrA, $arrB); print_r($replaced);
That’s it for this tutorial.
array_replace
array_replace() replaces the values of array with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values.
array_replace() is not recursive : it will replace values in the first array by whatever type is in the second array.
Parameters
The array in which elements are replaced.
Arrays from which elements will be extracted. Values from later arrays overwrite the previous values.
Return Values
Examples
Example #1 array_replace() example
$base = array( «orange» , «banana» , «apple» , «raspberry» );
$replacements = array( 0 => «pineapple» , 4 => «cherry» );
$replacements2 = array( 0 => «grape» );
?php
$basket = array_replace ( $base , $replacements , $replacements2 );
print_r ( $basket );
?>
The above example will output:
Array ( [0] => grape [1] => banana [2] => apple [3] => raspberry [4] => cherry )
See Also
- array_replace_recursive() — Replaces elements from passed arrays into the first array recursively
- array_merge() — Merge one or more arrays
User Contributed Notes 15 notes
// we wanted the output of only selected array_keys from a big array from a csv-table
// with different order of keys, with optional suppressing of empty or unused values
?php
$values = array
(
‘Article’ => ‘24497’ ,
‘Type’ => ‘LED’ ,
‘Socket’ => ‘E27’ ,
‘Dimmable’ => » ,
‘Wattage’ => ’10W’
);
$keys = array_fill_keys (array( ‘Article’ , ‘Wattage’ , ‘Dimmable’ , ‘Type’ , ‘Foobar’ ), » ); // wanted array with empty value
$allkeys = array_replace ( $keys , array_intersect_key ( $values , $keys )); // replace only the wanted keys
$notempty = array_filter ( $allkeys , ‘strlen’ ); // strlen used as the callback-function with 0==false
print » ;
print_r ( $allkeys );
print_r ( $notempty );
Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.
/**
* @param array $array
* @param array $replacements
* @param boolean $override
* @return array
*/
function array_replace_keys(array $array, array $replacements, $override = false) foreach ($replacements as $old => $new) if(is_int($new) || is_string($new)) if(array_key_exists($old, $array)) if(array_key_exists($new, $array) && $override === false) continue;
>
$array[$new] = $array[$old];
unset($array[$old]);
>
>
>
return $array;
>
To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:
$base = array( ‘id’ => NULL , ‘login’ => NULL , ‘credit’ => NULL );
$arr1 = array( ‘id’ => 2 , ‘login’ => NULL , ‘credit’ => 5 );
$arr2 = array( ‘id’ => NULL , ‘login’ => ‘john.doe’ , ‘credit’ => 100 );
$result = array_replace ( $base , $arr1 , $arr2 );
array(3) <
«id» => NULL
«login» => string(8) «john.doe»
«credit» => int(100)
>
array(3) <
«id» => int(2)
«login» => NULL
«credit» => int(5)
>
*/
?>
Function array_replace «replaces elements from passed arrays into the first array» — this means replace from top-right to first, then from top-right — 1 to first, etc, etc.
Here is a simple array_replace_keys function:
/**
* This function replaces the keys of an associate array by those supplied in the keys array
*
* @param $array target associative array in which the keys are intended to be replaced
* @param $keys associate array where search key => replace by key, for replacing respective keys
* @return array with replaced keys
*/
private function array_replace_keys($array, $keys)
foreach ($keys as $search => $replace) if ( isset($array[$search])) $array[$replace] = $array[$search];
unset($array[$search]);
>
>
print_r(array_replace_keys([‘one’=>’apple’, ‘two’=>’orange’], [‘one’=>’ett’, ‘two’=>’tvo’]);
// Output
array(
‘ett’=>’apple’,
‘tvo’=>’orange’
)
In some cases you might have a structured array from the database and one
of its nodes goes like this;
# a random node structure
$arr = array(
‘name’ => ‘some name’ ,
‘key2’ => ‘value2’ ,
‘title’ => ‘some title’ ,
‘key4’ => 4 ,
‘json’ => ‘[1,0,1,1,0]’
);
# capture these keys values into given order
$keys = array( ‘name’ , ‘json’ , ‘title’ );
?>
Now consider that you want to capture $arr values from $keys.
Assuming that you have a limitation to display the content into given keys
order, i.e. use it with a vsprintf, you could use the following
# string to transform
$string = «
name: %s, json: %s, title: %s
» ;
# flip keys once, we will use this twice
$keys = array_flip ( $keys );
# get values from $arr
$test = array_intersect_key ( $arr , $keys );
# still not good enough
echo vsprintf ( $string , $test );
// output —> name: some name, json: some title, title: [1,0,1,1,0]
# usage of array_replace to get exact order and save the day
$test = array_replace ( $keys , $test );
# exact output
echo vsprintf ( $string , $test );
// output —> name: some name, json: [1,0,1,1,0], title: some title
?>
I hope that this will save someone’s time.
Instead of calling this function, it’s often faster and simpler to do this instead:
$array_replaced = $array2 + $array1 ;
?>
If you need references to stay intact:
I got hit with a noob mistake. 🙂
When the function was called more than once, it threw a function redeclare error of course. The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision. A simple logical step was all that was needed.
With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own. Since this site has helped me so much, I felt the need to return the favor. 🙂
foreach ( $array2 as $key => $val ) <
if ( is_array ( $array2 [ $key ])) <
tier_parse ( $array1 [ $key ], $array2 [ $key ]);
> else <
$array1 [ $key ] = $array2 [ $key ];
>
>
return $array1 ;
>
?>
$array1 = array( «berries» => array( «strawberry» => array( «color» => «red» , «food» => «desserts» ), «dewberry» = array( «color» => «dark violet» , «food» => «pies» ), );
$array1 [ «berries» ][ «dewberry» ] = polecat_array_replace ( $array1 [ «berries» ][ «dewberry» ], $array2 );
?>
This is will replace the value for «food» for «dewberry» with «wine».
The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.
I hope this helps atleast one person for all that I’ve gained from this site.
PHP array_replace() Function
Replace the values of the first array ($a1) with the values from the second array ($a2):
Definition and Usage
The array_replace() function replaces the values of the first array with the values from following arrays.
Tip: You can assign one array to the function, or as many as you like.
If a key from array1 exists in array2, values from array1 will be replaced by the values from array2. If the key only exists in array1, it will be left as it is (See Example 1 below).
If a key exist in array2 and not in array1, it will be created in array1 (See Example 2 below).
If multiple arrays are used, values from later arrays will overwrite the previous ones (See Example 3 below).
Tip: Use array_replace_recursive() to replace the values of array1 with the values from following arrays recursively.
Syntax
Parameter Values
Parameter | Description |
---|---|
array1 | Required. Specifies an array |
array2 | Optional. Specifies an array which will replace the values of array1 |
array3. | Optional. Specifies more arrays to replace the values of array1 and array2, etc. Values from later arrays will overwrite the previous ones. |
Technical Details
More Examples
Example 1
If a key from array1 exists in array2, and if the key only exists in array1:
Example 2
If a key exists in array2 and not in array1:
Example 3
Using three arrays — the last array ($a3) will overwrite the previous ones ($a1 and $a2):
Example 4
Using numeric keys — If a key exists in array2 and not in array1: