Swapping Array Keys and Values in PHP

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

Array_flip($var_name);

 

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

swap1.jpg

The array_values() function returns all the values from the input array and indexes the array numerically.

Syntax

Array_values($var_name);

 

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

swap2.jpg

The array_keys() function returns all the keys or a subset of the keys of an array.

Syntax

Array_keys($var_name);

 

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


swap3.jpg

 

This array_reverse() function returns an array with elements in reverse order.

Syntax

($var_name);

 

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

swap4.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all