PHP how to get value from array if key is in a variable


Question

I have a key stored in a variable like so:

$key = 4;

I tried to get the relevant value like so:

$value = $array[$key];

but it failed. Help.

1
14
6/15/2011 7:43:26 AM

Accepted Answer

Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:

$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);

Output:

Array
(
    [0] => 4
)

Now:

$key = 4;
$value = $array[$key];
print $value;

Output:

Hello There
22
2/17/2010 3:01:26 PM

$value = ( array_key_exists($key, $array) && !empty($array[$key]) ) 
         ? $array[$key] 
         : 'non-existant or empty value key';

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon