php

PHP array_flip() Function

Sometimes, we may exchange keys to values and values to keys in an array. Is this possible in PHP arrays? Yes, By using array_flip() function.

array_flip() is used to exchange all the keys with their values in the given input array.

If there are no leys in the input array, by default it takes keys from 0. It takes only one parameter.

Syntax:
array_flip(array_input)
Where, array_input is the input array.

Example 1:
In this example, we will create an array named Flower with 4 values and flip the keys with values in the array.

<?php

//create an array named Flower with 4 values
$Flower1=array('flower_name','sepal','petal','area');
 
print_r("Actual array:");
print_r($Flower1);

//flip the keys-values
$finalized=array_flip($Flower1);

print_r("Final array:");
print_r($finalized);
?>

Output:

Here, we didn’t specify any keys in the actual array that has elements 10,20,30,40 and 50. So by default the keys will be 0,1,2,3 and 4. After flipping the array using array_flip() function, the keys and values were exchanged.

Example 2:
In this example, we will create an array named Flower with 5 values and flip the keys with values in the array.

<?php

//create an array named Flower with 5 values
$Flower1=array(10,20,30,40,50);
 
print_r("Actual array:");
print_r($Flower1);

//flip the keys-values
$finalized=array_flip($Flower1);

print_r("Final array:");
print_r($finalized);
?>

Output:

Here, we didn’t specify any keys in the actual array that has elements 10,20,30,40 and 50. So by default the keys will be 0,1,2,3 and 4. After flipping the array using array_flip() function, the keys and values were exchanged.

Example 3:
In this example, we will create an array named Flower with 4 key-value pairs and flip the keys with values in the array.

<?php

//create an array named Flower with 4 key-values.
$Flower1=array('flower_name'=>'lotus','sepal'=>4,'petal'=>3,'area'=>'water');
 
print_r("Actual array:");
print_r($Flower1);

//flip the keys-values
$finalized=array_flip($Flower1);

print_r("Final array:");
print_r($finalized);
?>

Output:

Here, the keys with respect to values are:
flower_name – lotus
sepal – 4
petal – 3
area – water

Now, after flipping this array, the result is
lotus – flower_name
4 – sepal
3 – petal
water – area

Conclusion

In this article, we saw how to exchange keys with values in an array using the array_flip() function.

If keys are not provided in an array, by default, it takes keys from 0. It takes the input array as a parameter. The applications of this are used in security. So, whenever we want to secure our message, we simply flip the keys with values, making the hacker unable to understand.

About the author

Gottumukkala Sravan Kumar

B tech-hon's in Information Technology; Known programming languages - Python, R , PHP MySQL; Published 500+ articles on computer science domain