arrays - Function with loop calling same function in PHP -
i'm having trouble. trying make work long time, decided ask here.
i have arrays inside it:
$myarray = [ ['string1','string2'], ['string3','string4'], ['string5',['string6','string7','string99']], ['string8','string9'] ];
i making function search s
function searcharray($array,$chave,$id) { foreach ($array $key) { if (is_array($key)) { if (($key[0] == $chave) && ($key[1] == $id)) { break; } else { searcharray($key,$chave,$id); } } } return $key; } $result = searcharray($myarray,'string6','string7'); print_r($result);
it supposed print ['string6','string7','string99']] it printing last "key" of array: ['string8','string9']
the break not working. after break, continue checking next arrays.
with these modification returns expected values:
<?php $myarray = [ ['string1','string2'], ['string3','string4'], ['string5',['string6','string7','string99']], ['string8','string9'] ]; function searcharray($array,$chave,$id) { foreach ($array $key) { if (is_array($key)) { if (($key[0] == $chave) && ($key[1] == $id)) { return $key; } else { $res = searcharray($key,$chave,$id); if($res !== false) { return $res; } } } } return false; } $result = searcharray($myarray,'string6','string7'); print_r($result);
the failure break on success. makes no sense.
you need return value on success. if no success return false. imagine may happen searched values not been found should return false.
Comments
Post a Comment