Reputation: 11812
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
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;
}
}
Upvotes: 1
Reputation: 13475
foreach ($results as $key => $value) {
$subKey = array_search(44556232, $value);
if (false !== $subkey) {
echo $key;
}
}
Upvotes: 0