I was wondering what is the best way to search keys in an array and return it's value. Something like array_search but for keys. Would a loop be the best way?
Array:
Array([20120425] => 409 [20120426] => 610 [20120427] => 277 [20120428] => 114 [20120429] => 32 [20120430] => 304 [20120501] => 828 [20120502] => 803 [20120503] => 276 [20120504] => 162)
Value I am searching for : 20120504
$foo = array( 'key1' => 'value 1', 'key1' => 'value 2', 'key2' => 'value 3', 'key2' => 'value 4', 'key3' => 'value 5' ); as you can see there are duplicate keys. All keys are strings. Array sits in a file and was created manually.
Arrays contains unique key. Hence if u are having multiple value for a single key, use a nested / multi-dimensional array. =) thats the best you got.
The array_keys() function returns an array containing the keys.
The key is already the ... ehm ... key
echo $array[20120504];
If you are unsure, if the key exists, test for it
$key = 20120504; $result = isset($array[$key]) ? $array[$key] : null;
Minor addition:
$result = @$array[$key] ?: null;
One may argue, that @
is bad, but keep it serious: This is more readable and straight forward, isn't?
Update: With PHP7 my previous example is possible without the error-silencer
$result = $array[$key] ?? null;
array_search('20120504', array_keys($your_array));
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