PHP array_replace() Function
In this chapter you will learn:
- Definition for PHP array_replace() Function
- Syntax for PHP array_replace() Function
- Parameter for PHP array_replace() Function
- Example - Replaces the values of the first array with the values
- Example for PHP array_replace() Function
- Example for If a key exists in array2 and not in array1
- Example - Using three arrays - the last array ($a3) will overwrite the previous ones ($a1 and $a2)
- Example - Using numeric keys - If a key exists in array2 and not in array1
Definition
The array_replace() function replaces the values of the first array with the values from following arrays.
Syntax
PHP array_replace() Function has the following syntax.
array_replace(array1,array2,array3...)
Parameter
Parameter | Is Required | Description |
---|---|---|
array1 | Required. | Array to replace |
array2 | Optional. | Array to replace array1 |
array3,... | Optional. | Array to replace array1 and array2, etc. |
Example 1
Replaces the values of the first array with the values from following arrays
<?php/*j a va2s .c o m*/
$a1=array("A","C");
$a2=array("B","D");
print_r(array_replace($a1,$a2));
?>
The code above generates the following result.
Example 2
If a key from array1 exists in array2, and if the key only exists in array1:
<?php/* j av a 2 s . c om*/
$a1=array("p"=>"PHP","j"=>"Java");
$a2=array("p"=>"Python");
print_r(array_replace($a1,$a2));
?>
The code above generates the following result.
Example 3
If a key exists in array2 and not in array1:
<?php/* j a va2 s . c o m*/
$a1=array("a"=>"red","java2s.com");
$a2=array("c"=>"orange","d"=>"burgundy");
print_r(array_replace($a1,$a2));
?>
The code above generates the following result.
Example 4
Using three arrays - the last array ($a3) will overwrite the previous ones ($a1 and $a2):
<?php/*from j a v a 2 s .c om*/
$a1=array("A","B");
$a2=array("A","java2s.com");
$a3=array("B","F");
print_r(array_replace($a1,$a2,$a3));
?>
The code above generates the following result.
Example 5
Using numeric keys - If a key exists in array2 and not in array1:
<?php//from j a v a 2s .com
$a1=array("A","B","C","D");
$a2=array(0=>"java2s.com",30=>"PHP");
print_r(array_replace($a1,$a2));
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP array_replace_recursive() Function
- Syntax for PHP array_replace_recursive() Function
- Parameter for PHP array_replace_recursive() Function
- Example for PHP array_replace_recursive() Function
- Example for PHP array_replace_recursive() Function with Multiple arrays
- Example - Differences between array_replace() and array_replace_recursive()