Reputation: 3941
I have a PHP array that prints the following information:
Array (
[0] => 23
[1] => 34
[2] => 35
[3] => 36
[4] => 37
[5] => 38
..<snip>..
)
I have the value and would like to cross reference it with the array to return a key. For instance, if I have a variable $value = 34
I would want to run a PHP function to return the key, which in this case is 1.
To be more specific, the array is stored in variable $pages
and the value is stored in variable $nextID
. I tried using array_search
with no luck:
How do I go about this?
Upvotes: 0
Views: 198
Reputation: 62
You could use foreach() like that:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
function mySearch($array, $search){
foreach($array as $key => $value){
if($value == $search){
return $key;
}
}
}
echo mySearch($arr, 3);
?>
Upvotes: 0
Reputation: 5896
array_search
is exactly what you're looking for. I'm not sure how you had problems with it.
$arr = [
5,
10,
15,
20
];
$value = 15;
echo array_search($value, $arr); // 2
Upvotes: 2