Here’s the following array:
Array
(
[1] => Array
(
[0] => 10
[1] => 13
)
[2] => Array
(
[0] => 8
[1] => 22
)
[3] => Array
(
[0] => 17
[1] => 14
)
)
Then I have
$chosenNumber = 17
What I need to know is:
First) if 17 is in the array
Second) the key it has (in this case [0])
Third) the index it belongs (in this case [3])
I was going to use the in_array function to solve first step but it seems it only works for strings ..
Thanks a ton!
function arraySearch($array, $searchFor) {
foreach($array as $key => $value) {
foreach($value as $key1 => $value1) {
if($value1 == $searchFor) {
return array("index" => $key, "key" => $key1);
}
}
}
return false;
}
print_r(arraySearch($your_array, 17));
You have used array_search function
$qkey=array_search(value,array);
You use array_search:
$index = array_search($chosenNumber, $myArray);
if($index){
$element = $myArray[$index];
}else{
// element not found
}
array_search returns false if the element was not found, the index of the element you were looking for otherwise.
If a value is in the array multiple times, it only returns the key of the first match. If you need all matches you need to use array_keys with the optional search_value parameter specified:
$indexes = array_keys($myArray, $chosenNumber);
This returns a (possibly empty) array of all indexes containing your search value.
You should look using these :
in_array()
array_search()
array_keys()
array_values()
array_key_exists()
in_array()
You can find more information here http://www.php.net/manual/en/function.array-search.php