Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if in_array() how to get the key as well?

Tags:

arrays

php

Struggling with a tiny problem.

I have an array:

Array (     [0] =>      [6] => 6     [3] => 5     [2] => 7 ) 

I am checking if a set value is in the array.

if(in_array(5, $array)) { //do something } else { // do something else } 

The thing is, when it find the value 5 in array, I really need the key to work with in my "do something".

In this case I need to set:

$key = 3; 

(key from the found value in_array).

Any suggestions?

like image 523
Tom Avatar asked Aug 06 '12 22:08

Tom


People also ask

How do I get keys in PHP?

PHP: array_keys() function The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

How get key from value in array in PHP?

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

What does in_array return in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do you check if an array contains a key?

The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.


2 Answers

array_search() is what you are looking for.

if (false !== $key = array_search(5, $array)) {     //do something } else {     // do something else } 
like image 53
DaveRandom Avatar answered Oct 13 '22 00:10

DaveRandom


If you only need the key of the first match, use array_search():

$key = array_search(5, $array); if ($key !== false) {     // Found... } 

If you need the keys of all entries that match a specific value, use array_keys():

$keys = array_keys($array, 5); if (count($keys) > 0) {     // At least one match... } 
like image 39
Niko Avatar answered Oct 12 '22 23:10

Niko