Yes I know... I'm new.. anyways
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.
Yes I know... I'm new.. anyways
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.
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
It should work the way you intended.
$array = array('value-0', 'value-1', 'value-2', 'value-3', 'value-4', 'value-5' /* … */);
$key = 4;;
$value = $array[$key];
echo $value; // value-4
But maybe there is no element with the key 4
. If you want to get the fiveth item no matter what key it has, you can use array_slice
:
$value = array_slice($array, 4, 1);
$value = ( array_key_exists($key, $array) && !empty($array[$key]) )
? $array[$key]
: 'non-existant or empty value key';
your code seems fine and it should work,,, check weather,, you are having $array[4]