Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    PHP Recursive Array Replace by Key or Value

    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.



    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.