I have got an multidimensional array on which I run a foreach loop.
I basically want to see if I've got the country_url stored in an database. If it is in the database then I'll echo "exists" but if it doesn't then I want to echo "doesn't exist". I don't want it to tell me for each array if it exists or not, but I want the foreach loop to tell me whether the country_url exists in one of the arrays or not.
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
echo "exists";
} else {
echo "doesn't exist";
}
}
Would anyone be able to help me out with this?
Try this:
$exist = false;
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
$exist = true;
break;
}
}
if ($exist){
echo "exists";
} else {
echo "doesn't exist";
}
You could store a variable and then use break
to terminate the loop once the item is found:
$exists = false;
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
$exists = true;
break;
}
}
if ($exists) {
echo "Success!";
}
This should work:
$text = "doesn't exist";
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
$text = "exists";
break;
}
}
echo $text;
As an alternative to the other answers, you could do the following:-
echo (in_array($country_url, array_map(function($v) { return $v['country_url']; }, $countriesForContinent))) ? 'exists' : 'does not exist';
This is probably slightless less efficient though as it will essentially loop through all $countriesForContinent
rather than finding a match and break
[ing].