Friday, October 17, 2025
HomeLanguagesPHP array_flip() Function

PHP array_flip() Function

This built-in function of PHP is used to exchange elements within an array, i.e., exchange all keys with their associated values in an array and vice-versa. We must remember that the values of the array need to be valid keys, i.e. they need to be either integer or string. A warning will be thrown if a value has the wrong type, and the key/value pair in question will not be included in the result.

Examples:

Input : array = ("aakash" => 20, "rishav" => 40, "gaurav" => 60)
Output:
        Array
        (
          [20] => aakash
          [40] => rishav
          [60] => gaurav
        )
Explanation: The keys and values are exchanged and the last key or value is taken.

Input : array = ("aakash" => "rani", "rishav" => "sristi", 
                 "gaurav" => "riya", "laxman" => "rani")
Output:
        Array
        (
          [rani] => laxman
          [sristi] => rishav
          [riya] => gaurav
        )

Syntax:

array array_flip($array)

Parameters: The function takes only one parameter $array that refers to the input array.

Return Type: This function returns another array, with the elements exchanged or flipped, it returns null if the input array is invalid.

Below program illustrates the working of array_flip() function in PHP:
Example 1:




<?php
  
// PHP function to illustrate the use of array_flip()
function Flip($array)
{
    $result = array_flip($array);
    return($result);
}
  
$array = array("aakash" => "rani", "rishav" => "sristi", 
               "gaurav" => "riya", "laxman" => "rani");
print_r(Flip($array));
  
?>


Output:

Array
(
    [rani] => laxman
    [sristi] => rishav
    [riya] => gaurav
)

If multiple values in the array are the same, then on the use of the array_flip() function, only the key with the maximum index (after swap) will be added to the array. (This is done to ensure that no keys have duplicates.)

Example 2:




<?php
// PHP program to array_flip() with multiple similar values
  
//function to use array_flip() 
function Flip($array)
{
    $result = array_flip($array);
    return($result);
}
  
  
//make the array
$array = array("a" => 1, "b" => 1, "c" => 2);
  
//print all resultant values
print_r(Flip($array)); 
  
?>


Output:

Array
(
    [1] => b
    [2] => c
)

References: http://php.net/manual/en/function.array-flip.php

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS