Prithviraj Mitra
Prithviraj Mitra

Reputation: 11812

Get the key from an array using php

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.

Upvotes: 1

Views: 50

Answers (3)

makallio85
makallio85

Reputation: 1356

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

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76666

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.

Upvotes: 1

JamesHalsall
JamesHalsall

Reputation: 13475

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

Upvotes: 0

Related Questions