Home » PHP

PHP array_flip() Function with Example

PHP array_flip() Function: Here, we are going to learn about the array_flip() function with example in PHP.
Submitted by IncludeHelp, on February 10, 2019

PHP array_filter() Function

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:

    array_flip(array) : array

Here, array is an input array. The function will return a new array by flipping keys as values and values as keys.

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".

Examples:

    Input:
    $arr = array("name" => "Prem", "age" => 28,"city" => "Gwalior");

    Function calling: 
    array_flip($arr);

    Output:
    Array
    (    
        [Prem] => name
        [28] => age
        [Gwalior] => city
    )

PHP code 1: Example with unique values.

<?php
    // input array
    $arr = array("name" => "Prem", "age" => 28,"city" => "Gwalior");
    
    // flipping array
    $temp = array_flip($arr);
    
    print_r ($temp);
?>

Output

Array
(    
    [Prem] => name
    [28] => age
    [Gwalior] => city
)

PHP code 2: Example without unique values.

<?php
    // persons array 
    $arr = array("a" => "Hello", "b" => "Hello", "c" => "Hi");
    
    // flipping array
    $temp = array_flip($arr);
    
    print_r ($temp);
?>

Output

Array
(
    [Hello] => b
    [Hi] => c
)






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.