I want a different variable for stuff which pass stristr but must not contain anything except those 3 different things
I have this following code:-
$unitedstatess = stristr($ad['country'], 'united states');
$unitedkingdom = stristr($ad['country'], 'united kingdom');
$canada = stristr($ad['country'], 'canada');
if (($unitedstatess != FALSE) OR ($unitedkingdom != FALSE) OR ($canada != FALSE)) { $adsptc4.=$tempcode; }
If $ad['country'] has united states, united kingdom or canada then it should pass or else if there are different values other than the above it should go in else rest.
Example:- Ad 1 has: ( united states;united kingdom ) > Then it should pass as $adsptc4 Ad 2 has: ( united states;italy ) > Then it should fail.
Let me know if you did not understand something.
<?
$ad['country'] = "United States;canada";
$allowed = array(
'united states' => true,
'united kingdom' => true,
'canada' => true
);
$countries = strtolower($ad['country']);
$countries = explode(";", $countries);
$found = false;
foreach($countries as $c) {
if(isset($allowed[$c]) == FALSE) {
$found = true;
break;
}
}
if($found != t开发者_Go百科rue) {
echo "true";
}
else {
echo "false";
}
?>
Works good, Let me know if there are any drawbacks out of it.
You could store all "allowed" entries in an array. and check it with array_search() or isset()
array_search():
$allowed = array('united states', 'united kingdom', 'canada');
$input = strtolower($ad['country']);
if(array_search($input, $allowed) !== false) {
//your true code
}
else {
//your else code
}
isset():
$allowed = array(
'united states' => true,
'united kingdom' => true,
'canada' => true
);
$input = strtolower($ad['country']);
if(isset($allowed[$input])) {
//true
}
else {
//false
}
to find the entries, they have to be completely the same, therefor all entries in $allowed are lowercase and your input $ad['country'] is changed to lower-case.
Both options are possible. I prefer the second one because I can give some extra information (instead of true I could give a special array or something else) which could be processed.
After your second edit:
You can explode the given countries and check each:
$countries = strtolower($ad['country']);
$countries = explode(";", $countries);
$found = true;
foreach($countries as $c) {
$c = trim($c);
if(!isset($allowed[$c])) {
$found = false;
break;
}
}
if($found == true) {
//true
}
else {
//false
}
精彩评论