I would like to find a given value and return the key, Ive tried many ways of solving this but none work. I spent many hours testing diffrent solutions but no luck so far, yet this is such a simple task. Here are some functions that I have tried but none return the correct key: (in this case should be 0)
This returns nothing:
$mapkey = $data['srv']['map_image'];
$ikey = array_search($mapkey, $data['srv']['maps']);
if ($ikey !== FALSE) {
// Match made.
}
I get '3' when it should be '0', from this one:
foreach ($data['srv']['maps'] as $key => $value) {
$mapkey = ($data['srv']['map_image']);
if ($value === $mapkey && $data['srv']['maps'][$key]['map_image'] === $mapkey) {
return $key;
}
}
I get nothing from this and should be '0':
$mapkey = $data['srv']['map_image'];
foreach ($data['srv']['maps'] as $key => $val) {
if ($val === $mapkey) {
return $key;
}
}
This one completely crashes the web page:
function recursive_array_search($mapkey,$data) {
foreach($data['srv']['maps'] as $key=>$val) {
$mapkey = $data['srv']['map_image'];
$imagekey=$key;
if($mapkey===$val OR (is_array($val) && recursive_array_search($mapkey,$val) !== false)) {
return $imagekey;
}
}
return false;
}
Example of the $data array:
Array
(
[srv] => Array
(
[map_name] => map 1
[map_image] => MP_001
[maps] => Array
(
[0] => Array
(
[map_name] => map 1
[map_image] => mp_001
)
[1] => Array
(
[map_name] => map 2
[map_image] => mp_017
)
[2] => Array
(
[map_name] => map 3
[map_image] => mp_014
)
[3] => Array
(
[map_name] => map 4
[map_image] => mp_007
)
)
)
)
In the first one, you are searching directly inside the $data['srv']['maps']
which contains keys like 0 , 1 . But you have to search inside all the 0 , 1s so it fails.
In second one, if you remove the first condition it shall work. Bcoz in first condition you are comparing a value with an array ($value
) is an array.
The above mistake you are doing in third also.
Fourth is too complicated. Best thing is thata you remove the first condition from second one.
Update: As per your update, for comparison they shall be in same case ;-)
Ok I have come up with a solution.
foreach ($data['srv']['maps'] as $key => $value) {
$mapkey = strtolower($data['srv']['map_image']);
if ($mapkey == $data['srv']['maps'][$key]['map_image']) {
$imgkey = $key;
}
}
echo '<pre>';
print_r($imgkey);
echo '</pre>';
Returns '0'
The problem I had was where the code was being placed and the fact I couldn't have $key returned as it broke the rest of the code.