1

I have an array with the following format

Array
(
    [messages] => Array
        (
            [42321316] => 44556232
        )

    [text] => test message
    [count] => 1
)

I am trying to get the number '42321316' using following code

foreach($results as $k=>$y)
{
    echo $results[$k];
}

But it prints the values instead of getting the key of second array element.

2
  • foreach(array_keys($results) as $key){ echo $key."\n"; } Commented Feb 13, 2014 at 19:20
  • There is a nested array. Commented Feb 13, 2014 at 19:22

3 Answers 3

1

Use array_search() to achieve this:

$key = array_search('44556232', $results['messages']);
echo $key; // => 42321316

The above code is useful only if you know the array index beforehand. If the search key is dynamic, then you need a dynamic solution as well:

$keyToSearchFor = '44556232';

foreach ($results as $key => $value) {
    if (is_array($value)) {
        echo array_search($keyToSearchFor, $value);
        break;
    }
}

Demo.

Sign up to request clarification or add additional context in comments.

Comments

0
foreach ($results as $key => $value) {
    $subKey = array_search(44556232, $value);
    if (false !== $subkey) {
        echo $key;
    }
}

Comments

0

You should do echo $results ['messages'][42321316]; instead.

1 Comment

OP wants the key, not the value.

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.