Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to replace array elements with another array elements?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.02k
    Comment on it

    Hello friends,

    Today we will learn how to replace array element with other elements. In PHP, array_replace() function is used to replace the array elements with another array elements with the help of key. That is, elements of the first array will be replaced with the elements of second array having matching key.

    Syntax:

    array_replace ( array $array1 , array $array2 [, array $... ] )

    $array1 is the first array whose elements need to be replaced with the other array passed as a parameter with the help of the key of arrays. That is, if $array1 keys matched with $array2 elements then the $array1 elements will be removed with $array1 elements. You can pass more that 1 array for replacement. That is, if there is third array then it will also compared with $array1 and all keys matched will be replaced.

    Let's take an example to understand this topic.

    
    <?php
    $a = array("key1"=>"1", "key2"=>"2", "key3"=>"3");
    $a1 = array("key1"=>"new val of key1");
    $a2 = array("key3"=>"new value of key3");
    $a3 = array_replace($a, $a1, $a2);
    print_r($a3);
    echo "<br>";
    $b = array("abc", "pqr", "mno", "xyz");
    $b1 = array(0 => "new abc", 4 => "new xyz");
    $b2 = array(0 => "again abc");
    
    $b3 = array_replace($b, $b1, $b2);
    print_r($b3);
    ?>
    

    In above example, $a, $a1, $a3, $a4 are associative arrays and  $b, $b1, $b2, $b3 are indexed arrays.  $a, $b are the arrays whose elements are needed to be replaced with the $a1, $a2, $b1, $b2 elements. $a3 and $b3 array are the output after the replacement.

    After running the script in the browser output will be:

    Array ( [key1] => new val of key1 [key2] => 2 [key3] => new value of key3 )
    Array ( [0] => again abc [1] => pqr [2] => mno [3] => xyz [4] => new xyz ) 

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: