2

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

4 Answers 4

6

array_search is what you need.

$var = 10;
$key = array_search($var, $hours);
Sign up to request clarification or add additional context in comments.

1 Comment

Not sure the second example is any more useful than just calling array_search directly?
2
 $key = array_search($array, 10);

Comments

2

Use the function array_search

$key = array_search(10,$aray); // $key will get 5 in your case.

the syntax is:

key = array_search(value_to_search,array);

Comments

0
Syntax : array_search ( Search Keyword here , Array here);  

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red

$key = array_search('green', $array);   // $key = 2;

$key = array_search('red', $array);  // $key = 1

1 Comment

This question already had an accepted answer more than 6 years ago. Your answer only provides a guide on how to use array_search, rather than adapting it to the question's data. Please only add alternative answers to long-dead questions when they provide a new approach that improves upon the accepted answer.

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.