AppDividend
Latest Code Tutorials

PHP array_flip: How to Flip Array in PHP

You often need to flip the array values while developing a project. The in_array() method becomes relatively slow, but you can flip the big array and then use the isset() function to obtain the same result in a much faster way. Let’s see how to use the array_flip() method to flip the array values.

PHP array flip

The array_flip() is a built-in PHP function that flips/exchanges all keys with their associated values in the array. The array_flip() function returns the array in flip order; for example, keys from the array become values, and values from the array become keys.

The array’s values need to be the valid keys, i.e., they need to be either an integer or string. A warning will be emitted if the value has the wrong type, and the key-value pair in question will not be included in the result.

Syntax

array_flip(array);

Arguments

The array parameter is necessary, and it specifies the array of key/value pairs to be flipped.

Example

See the following example.

<?php

// app.php

$brands = [
  'Louis Vuitton' => "LV",
  'Hermès' => "H",
  'Gucci' => "G",
  'Prada' => "P",
  'Chanel' => "C",
  'Cartier' => "Ca"
];
$flip = array_flip($brands);
print_r($flip);

See the below output.

PHP Array Flip Example

Remember one thing that it can only flip STRING and INTEGER values. Otherwise, it will give a warning.

If you try to flip the non-associative array, then the indexes become the value and values become keys.

See the following code.

<?php

// app.php

$brands = [
  'Louis Vuitton',
  'Hermès',
  'Gucci',
  'Prada',
  'Chanel',
  'Cartier'
];
$flip = array_flip($brands);
print_r($flip);

See the below output.

PHP array_flip() Function Tutorial

Remove duplicate values using array_flip()

To remove duplicate array values in PHP, use the array_flip() method. The array_flip() method will remove duplicate values in the original array when you flip either an associative or numeric array. As you might expect it’s the earlier of two duplicates that are lost.

See the below code.

<?php

// app.php

$brands = [
  'Louis Vuitton',
  'Hermès',
  'Gucci',
  'Prada',
  'Louis Vuitton',
  'Hermès',
];
$flip = array_flip($brands);
print_r($flip);

Louis Vuitton and Hermes are duplicate values in the above code, so the earlier duplicates are removed. Depending on the requirement, it may be good or bad, but no error is thrown.

See the below output.

Remove duplicate values using array_flip()

That’s it for this example.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.