Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Swap keys with their associated values in an array using PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 965
    Comment on it

    This article demonstrates a PHP function which can be used for swapping of keys with values in an array. array_flip() is the function which accepts an array as parameter and exchange the keys with their associated values in an array. This function returns an array with flipped values.


    Note :

    • If any value has multiple occurrences, the last key will be used as value other keys will be lost.
    • Warning will be generated, if the values of an array are not valid keys i.e. integer or string values.

    Syntax : array_flip(array)

    array : Specifies an array, whose key/value pairs have to be flipped.


    Example :

    <?php
       $arr = array(1 => "a", 2 => "b", 3 => "c", 4 => "d", 5 => "e");
       print_r($arr);
       echo "<br>";
       echo "After Flip : ";
       print_r(array_flip($arr));
    ?>
    

    Output :
    Array ( [1] => a [2] => b [3] => c [4] => d [5] => e )
    After Flip : Array ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 )


 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: