Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php search array key and get value [duplicate]

Tags:

php

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

like image 668
Keith Power Avatar asked May 05 '12 00:05

Keith Power


People also ask

How do I find duplicate keys in an array?

$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.

Can PHP arrays have duplicate keys?

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.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


2 Answers

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; 
like image 127
KingCrunch Avatar answered Sep 21 '22 07:09

KingCrunch


array_search('20120504', array_keys($your_array)); 
like image 26
Marc B Avatar answered Sep 21 '22 07:09

Marc B