[php] php search array key and get value

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

This question is related to php

The answer is


<?php

// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
  echo $search_array[20120504];
}

// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
  echo $search_array[20120504];
}

// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
  echo $search_array[20120504];
}

?>

Here is an example straight from PHP.net

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

in the foreach you can do a comparison of each key to something that you are looking for


array_search('20120504', array_keys($your_array));