PHP Array Flip

PHP Array Flip

Last Updated on Feb 14, 2023

Array Flip

Array flip is very simple yet useful array function that helps you flip and array.

What does it mean to flip an array? 

Well it means to change the array in a way that the keys become the values and the values become the keys.

Let’s see an example

$array = [
   'twitter'  => 'pratham',
   'feedhive' => 'simon',
   'php'      => 'amir'
];
$flipped = array_flip($array);
print_r($flipped);
Array (
//    [pratham]   => twitter
//    [simon]     => feedhive
//    [amir]      => php
//)

You should note 2 things:

1- the values of the original array can be either int or string. Otherwise you’ll get an error

For example you can’t have something like this

$array = [
   'twitter'  => 'pratham',
   'feedhive' => 'simon',
   'php'      => true
];

2- if the original array has duplicate values, the key of the last one will be assigned as the value of the new flipped array.

For example

$array = [
   'twitter'  => 'pratham',
   'feedhive' => 'simon',
   'php'      => 'amir',
   'css'      => 'pratham'
];
$flipped = array_flip($array);
print_r($flipped);
// Array (
//  [pratham]   => css
//  [simon]     => feedhive
//  [amir]      => php
// )

Conclusion

Now you know about array flip function in PHP.

I recommend you to open a PHP files and try to define an array. then try to flip it and see the result.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • array flip function in PHP
  • limitation of array flip

Category: programming

Tags: #php #array

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses