Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search array and get array key

I have an array, which I'd like to search for a value in and retreive the array key if it exists, but not sure how to even go about doing that. Here's my array:

Array
(
    [hours] => Array
        (
            [0] => 5
            [1] => 5
            [2] => 6
            [3] => 6
            [4] => 8
            [5] => 10
        )
)

So I'd like to search the hours array for 10, if 10 exists in the array, I want the key (5) to be returned. If that makes sense?

Am trying to do it dynamically so the search string (10) will change, but I figure if I can get it working for number 10, I can get it working with a variable number :)

like image 219
SoulieBaby Avatar asked Mar 07 '26 23:03

SoulieBaby


1 Answers

array_search is what you need.

$var = 10;
$key = array_search($var, $hours);
like image 62
Anthony Forloney Avatar answered Mar 09 '26 12:03

Anthony Forloney