PHP array_replace() Function
PHP array_replace() Function
The array_replace() function in PHP replaces the elements from passed arrays into the first array with values having the same keys in each of the following arrays.
Syntax
array_replace ( array $array1 [, array $... ] )
Parameter
array(required)- This parameter represents the input array in which elements are replaced.
...(optional)- This parameter signifies one or more arrays from which elements will be extracted.
Return
This function either returns the replaced array or it returns NULL if an error occurs.
Example 1
"e", 2 => "i"); //Return an array after Replacing the elements as passed in replacements array $replaced_array=array_replace($array, $replacements); echo("\nReplaced elements are:\n"); print_r($replacements); echo("Replaced Array: \n"); //printing the replaced array print_r($replaced_array); ?>
Output
Actual Array: Array ( [0] => a [1] => b [2] => c [3] => o [4] => u ) Replaced elements are: Array ( [1] => e [2] => i ) Replaced Array: Array ( [0] => a [1] => e [2] => i [3] => o [4] => u )
Example 2
"pineapple", 4 => "cherry"); $replacements2 = array(0 => "grape"); //Return an array after Replacing the elements from replacements arrays $replaced_array=array_replace($array, $replacements1,$replacements2); echo("Replaced Array: \n"); //printing the replaced array print_r($replaced_array); ?>
Output
Actual Array: Array ( [0] => apple [1] => banana [2] => guava [3] => orange [4] => strawberry ) Replaced Array: Array ( [0] => grape [1] => banana [2] => guava [3] => orange [4] => cherry )
Example 3
"pineapple", 4 => "cherry"); //Return an array after Replacing the elements from replacements arrays $replaced_array=array_replace($array, $replacements1); echo("Replaced Array: \n"); //printing the replaced array print_r($replaced_array); ?>
Output
Actual Array: Array ( [0] => ) Replaced Array: Array ( [0] => pineapple [4] => cherry )