Home »
PHP
PHP Array array_flip() Function (With Examples)
In this tutorial, we will learn about the PHP array_flip() function with its usage, syntax, parameters, return value, and examples.
By IncludeHelp Last updated : December 31, 2023
PHP array_flip() Function
The array_flip() function is used to flip the array keys and values, it returns an array by flipping all values as keys and all keys as values.
Syntax
The syntax of the array_flip() function:
array_flip(array) : array
Parameters
The parameters of the array_flip() function:
- array is an input array. The function will return a new array by flipping keys as values and values as keys.
Return Value
The return type of this method is array, it returns the flipped array.
As we know, an array contains unique keys. If we flip the array and the values are common then the last value will be considered as key and its key will be considered as value.
For example – there are two values are common "a" => "Hello" and "b" => "Hello", in this case second element's value will be key and its key will be value: "Hello" => "b".
Sample Input/Output
Input:
$arr = array("name" => "Prem", "age" => 28,"city" => "Gwalior");
Function calling:
array_flip($arr);
Output:
Array
(
[Prem] => name
[28] => age
[Gwalior] => city
)
PHP array_flip() Function Example 1: With unique values
<?php
// input array
$arr = array("name" => "Prem", "age" => 28,"city" => "Gwalior");
// flipping array
$temp = array_flip($arr);
print_r ($temp);
?>
Output
The output of the above example is:
Array
(
[Prem] => name
[28] => age
[Gwalior] => city
)
PHP array_flip() Function Example 1: Without unique values
<?php
// persons array
$arr = array("a" => "Hello", "b" => "Hello", "c" => "Hi");
// flipping array
$temp = array_flip($arr);
print_r ($temp);
?>
Output
The output of the above example is:
Array
(
[Hello] => b
[Hi] => c
)
To understand the above examples, you should have the basic knowledge of the following PHP topics: