Introduction
In this article I will explain how to swap Array Keys and Values in PHP. To do this I will use some important array functions.
The array_flip() function exchanges all keys with their associated values in an array.
Syntax
Parameter |
|
Var_name |
An array of key/value pairs to be flipped or swapped. |
Return Value
This function returns the flipped array on success and NULL on failure.
Example
<?php
$swap = array("a" => 0, "b" => 1, "c" => 2,"d" => 3,"e" => 3,"f" => 4);
$swap = array_flip($swap);
echo "<pre>";print_r($swap);
?>
Output
The array_values() function returns all the values from the input array and indexes the array numerically.
Syntax
Parameter |
|
Var_name |
Pass the array variable name |
Return Value
This function returns an indexed array of values.
Example
<?php
$array = array("size" => "AB", "color" => "PINK");
echo "<pre>";print_r(array_values($array));
?>
Output
The array_keys() function returns all the keys or a subset of the keys of an array.
Syntax
Parameter |
|
Var_name |
An array containing keys to return. |
Return Value
This function returns an array of all the keys in the input.
Example
<?php
$array = array(0 => 200, "color" => "White");
echo "<pre>";print_r(array_keys($array));
$array = array("PHP", ".Net", "Java", "SAP", "SAP");
echo "<pre>";print_r(array_keys($array, "SAP"));
$array = array("name" => array("you", "yes", "tom"),
"category" => array("obc", "general", "sc/st"));
echo "<pre>";print_r(array_keys($array));
?>
Output
This array_reverse() function returns an array with elements in reverse order.
Syntax
Parameter |
|
Var_name |
Input the array |
Return Value
This function returns the array reversed.
Example
<?php
$input = array("php", 5, array("green", "pink"));
$reverse= array_reverse($input);
$preserved = array_reverse($input, true);
echo "<pre>";print_r($input);
echo "<pre>";print_r($reverse);
echo "<pre>";print_r($preserved);
?>
Output