Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap an array element's key and value

Is there a function which makes:

$array['blue'] = 'Color';

To:

$array['Color'] = 'blue'

And also, is there a limit on what characters can go inside an array index?

like image 947
Ali Avatar asked Feb 13 '26 16:02

Ali


2 Answers

array_flip() exchanges all keys with their associated values in an array. Any characters can be used in the key, however keep in mind that keys must be unique, so:

$array['blue'] = 'Color';
$array['red']  = 'Color';
$array = array_flip($array);

Yields only:

Array
(
    [Color] => red
)
like image 134
usoban Avatar answered Feb 15 '26 05:02

usoban


As for the type of characters that can be used as a key, there seems to be no limit (accents, quotes, and other characters are accepted).

As for the size limit, there isn't any either, the only restriction is the script's memory limit (see "What is the max key size for an array in PHP?"

Couldn't find any official PHP documentation mentioning this though.

like image 20
altermativ Avatar answered Feb 15 '26 06:02

altermativ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!