PHP Recursive Array Replace by Key or Value

These functions allow you to get replace PHP array value by using 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 major 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 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 by value.


Courses
Subscribe Updates via Email

Join 49,000+ W3schools lovers and get all the latest tutorials, programs, algorithms in your inbox.