- PHP array_replace() function
- What is the syntax of the array_replace function in PHP?
- Examples of array_replace function
- What is the difference between array_replace and array_replace_recursive function?
- array_replace
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- 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
The array_replace function replaces the values from the first array with the values of the following arrays given to the function. You will get a clear understanding after going through the syntax and examples below.
You can assign one or multiple arrays to the array_replace function.
There are the following scenarios to be focused on for the array_replace function.
- If a key exist in array 1 found in the array 2, it will be replaced by the value of array 2.
- If the array 1 key does not exist in any of the following arrays, it will remain same in the result.
- If array 1 does not contains any key that the following arrays do, they will be created in the array 1.
- If multiple arrays are used, the latest array value will overwrite the value in the previous array.
What is the syntax of the array_replace function in PHP?
array_replace(array1, array2, array3, . )
Parameter | Description |
---|---|
array1 | Array to replace the values of – Required |
array2 | Array to replace the values with – Optional |
array3,… | More arrays to replace the values. Values from the last most array overwrite the previous ones – Optional |
array_replace function in PHP
Examples of array_replace function
In the above example, we replace the values of one array with the values of another array.
"Red","key2"=>"Green"); $array_2=array("key1"=>"Blue","Yellow"); print_r(array_replace($a1,$a2)); ?>
The above example shows the scenario in which the key of the first array exists in the second array so it will be replaced by the second array value. Also, the first array contains a key that does not exist in the second array. You must execute this script and see the output.
"1","2"); $array_2=array("a"=>"3","b"=>"4"); print_r(array_replace($a1,$a2)); ?>
In the above example, keys exist in array 2 but not in the first array.
The above example shows that the last array will replace the values of the previous two arrays.
"O",3=>"B"); print_r(array_replace($array_1,$array_2)); ?>
The above example shows that the numeric key exists in the second array but not in the first array.
What is the difference between array_replace and array_replace_recursive function?
Understand and execute the following example script to have a clear difference between the array_replace and array_replace_recursive function.
array("1"),"b"=>array("2","3"),); $array_2=array("a"=>array("4"),"b"=>array("5")); $res=array_replace_recursive($array_1,$array_2); print_r($res); $result=array_replace($array_1,$array_2); print_r($res); ?>
array_replace
array_replace() замещает значения массива array1 значениями с такими же ключами из других переданных массивов. Если ключ из первого массива присутствует во втором массиве, его значение заменяется на значение из второго массива. Если ключ есть во втором массиве, но отсутствует в первом — он будет создан в первом массиве. Если ключ присутствует только в первом массиве, то сохранится как есть. Если для замены передано несколько массивов, они будут обработаны в порядке передачи и более поздние массивы будут перезаписывать значения из предыдущих.
array_replace() не рекурсивная: значения первого массива будут заменены вне зависимости от типа значений второго массива, даже если это будут вложенные массивы.
Список параметров
Массив, элементы которого требуется заменить.
Массив, элементами которого будут заменяться элементы первого массива.
Еще массивы, из которых будут браться элементы для замены. Значения следующего массива затирают значения предыдущего.
Возвращаемые значения
Возвращает массив ( array ) или NULL в случае ошибки.
Примеры
Пример #1 Пример использования array_replace()
$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 );
?>
Результат выполнения данного примера:
Array ( [0] => grape [1] => banana [2] => apple [3] => raspberry [4] => cherry )
Смотрите также
- array_replace_recursive() — Рекурсивно заменяет элементы первого массива элементами переданных массивов
- array_merge() — Сливает один или большее количество массивов
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: