This PHP ArrayReplace function allows you to change the PHP array value using an array key or value.
I recently came across this issue in my project, where I need to replace PHP array value by array key.
Here's the PHP ArrayReplace function I wrote to take care of this significant task.
Example:
<?php
function ArrayReplace($Array, $Find, $Replace){
if(is_array($Array)){
foreach($Array as $Key=>$Val) {
if(is_array($Array[$Key])){
$Array[$Key] = ArrayReplace($Array[$Key], $Find, $Replace);
}else{
if($Key === $Find) {
$Array[$Key] = $Replace;
}
}
}
}
return $Array;
}
//Define Array
$Array = array('FirstName'=>"Alex",'DOB'=>'1985-06-12');
echo '<pre>',print_r($Array,1),'</pre>';
//Replace in Array
$Array = ArrayReplace($Array,'DOB',date('j \of\ F Y',strtotime($Array['DOB'])));
echo '<pre>',print_r($Array,1),'</pre>';
?>
I recently came across this issue when having to deal with a multidimensional array that I needed to have scrubbed for certain values. Here in the above example, I have replaced DOB value in the array by using the array key.
Program Output:
Array
(
[FirstName] => Alex
[DOB] => 1985-06-12
)
Array
(
[FirstName] => Alex
[DOB] => 12 of June 1985
)
After minor modification, you can also use this function to replace it by value.