Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

What is the array_flip method in PHP?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The array_flip method exchanges the keys and values of an array. This means all the keys are converted to values and all the values are converted to keys.

Syntax

array_flip(array $array_to_flip): array

This method returns a new array.

Code

<?php
$arr = array(1 => "one", 2 => "two", 3 => "three");
echo "The array is \n";
print_r($arr);
echo "\nAfter Flipping \n ";
print_r(array_flip($arr));
?>

In the code above, we created an array.

one => 1
two => 2
three => 3

We then call the array_flip method by passing the created array, which will flip the keys and values of the passed array and return a new array. The returned array will be:

1  => one
2 => two
3 => three

Make sure all the values of the passed array are either string or integer values, otherwise a warning will be thrown and the value will be skipped. For example:

<?php
$arr = array(1 => "one", 2 => array());
print_r(array_flip($arr));
?>

In the code above, the value for the key 2 is an array, which cannot be used as a key, so we will get a warning and that entry will be skipped. The returned array from the array_flip method will be:

one => 1

RELATED TAGS

php
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring