array_flip()

Published Jul 17, 2023
Contribute to Docs

The array_flip() method is used to interchange the keys and values of an array. It creates a new array where the original array’s values become the keys, and the keys become the values. This function can be useful in situations where it’s needed to quickly lookup keys based on their previous values.

Syntax

array_flip($original_array)

The array_flip() function has one required parameter:

  • $original_array: The array to be flipped.

Example

The following example uses the array_flip() function to flip $original_array :

<?php
$original_array = array(
'apple' => 'fruit',
'carrot' => 'vegetable'
);
$flipped_array = array_flip($original_array);
print_r($flipped_array);
?>

The example will result in the following output:

Array (
['fruit'] => 'apple',
['vegetable'] => 'carrot'
)

Codebyte Example

This example is runnable and uses the array_flip() function:

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn PHP on Codecademy