16

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.

3
  • 2
    What do you mean "failed," any errors? Commented Feb 17, 2010 at 14:43
  • 2
    Are you sure there's a value in $array[4]? Because your syntax is correct - look elsewhere for the problem. Commented Feb 17, 2010 at 14:44
  • 2
    Could you add some more details, for example which is the contents of $array ? Commented Feb 17, 2010 at 14:44

4 Answers 4

27

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.

    protected function _getArrayValue($array, $key, $default = null)
    {
        if (isset($array[$key])) return $array[$key];
        return $default;
    }

hope it helps.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.