Home >>PHP Array Functions >PHP array_replace() Function

PHP array_replace() Function

PHP array_replace() Function

PHP array_replace() Function in PHP language generally replaces the values of the first array with the values from the following arrays.

Please note that the programmer can assign one array to the function or as many as they like to add.

In case, a key from the array1 exists in the array2 then the values from array1 will be generally replaced by the values from the array2. In case, the key only exists in the array1 then it will be left as it is without any change.

Here is another case in which a key exist in the array2 and not in the array1 then this will be created in the array1.
However, if the multiple arrays are being used, then the values from later arrays will generally overwrite the previous ones.

Please note that use of the array_replace_recursive() function in order to replace the values of array1 with the values from the following arrays recursively will be better.

Syntax:

array_replace(array1, array2, array3, ...)

Parameter Values

Parameter Description
array1 This is generally used to specify an array and it is required.
array2 This parameter generally used to specify an array that will be replacing the values of array1. However, this is optional.
array3,... This parameter is used in order to specify more arrays to replace the values of array1 and array2, etc. and this is also optional. The values from later arrays will usually overwrite the previous ones.

Here, is an example of array_replace() Function in PHP:

<html>
<body>
<?php
$gautam=array("arr"=>"php","java"=>"python");
$arya=array("arr"=>"mysql","seo");
print_r(array_replace($gautam,$arya));
?>
</body>
</html>
Output:
 Array (
 	 [arr] => mysql 
 	 [java] => python 
 	 [0] => seo 
 	 )

Example 2:

<html>
<body>
<?php
$find = array("phptpoint","phptpoint.com");
$replace = array("xyz");
$arya = array("wel","come","!!!");
print_r(str_replace($find,$replace,$arya));
?>
</body>
</html>
Output:
Array (
	 [0] => wel 
	 [1] => come 
	 [2] => !!!
	  )

No Sidebar ads