Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_flip

Swaps keys and values.

Syntax

array_flip(array $array): array

Parameters

ParameterTypeDescription
$arrayarrayThe source array.

Return value

arrayAn array in which the values became the keys.

Examples

Swapping keys and values:

<?php
 
echo json_encode(array_flip(['a' => 1, 'b' => 2]));

Output:

{"1":"a","2":"b"}

A fast membership check:

<?php
 
$allowed = array_flip(['jpg', 'png', 'webp']);
 
var_dump(isset($allowed['png']));
var_dump(isset($allowed['exe']));

Output:

bool(true)
bool(false)

Notes

The values must be strings or numbers. With repeated values the last key wins.

See also

  • array_combine — Creates an array from two lists: keys and values.
  • array_search — Searches an array for a value and returns its key.

In the tutorial

  • Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.

Thanks for reading!

Donate to the site — we work hard for you.