What is the MOST EFFICIENT way to have an array of values and turn it into an array of keys? I'd really like to avoid any foreach loop...
$in = array(
'red',
'green',
'blue'
);
INTO
$out = array(
'red' => NULL,
'green' => NULL,
'blue' => NULL
);
If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).
Your code is the exact equivalent of: $assoc = array_fill_keys(array(1, 2, 3, 4, 5), 1); // or $assoc = array_fill_keys(range(1, 5), 1);
To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.
The array_keys() function returns an array containing the keys.
Use PHP's array_flip
function.
array_fill_keys
:
$out = array_fill_keys($in, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With