note 105614 modified in function.strstr by danbrown
| From: | danbrown@php.net | Date: | Thu, 27 Oct 2011 18:40:58 +0000 |
| Subject: | note 105614 modified in function.strstr by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-184177@lists.php.net to get a copy of this message | ||
I explained this to my newbies the difference though it would be good to demonstrate this here. If
you are evaluating a list you cannot use strstr as it looks for any occurance. The correct way is
the function which evaluates a true or false on the exact value to check.
In the following example I have a list of promotion ids I want to evaluate whether or not a
promotion exists:
<?php
//Wrong
$promotion = strstr("25,56","2");
if($promotion){
echo "found";
}else{
echo "not found";
}
//right
function detectPromotion($string,$promotion){
foreach(explode(",",$string) as $promotionToCheck){
echo "checkin ".$promotionToCheck."==".$promotion."<br/>";
if($promotionToCheck==$promotion){
$promotionFound=true;
}
}
return $promotionFound;
}
echo detectPromotion("2,56","2");
?>
--was--
I explained this to my newbies the difference though it would be good to demonstrate this here. If
you are evaluating a list you cannot use strstr as it looks for any occurance. The correct way is
the function which evaluates a true or false on the exact value to check.
In the following example I have a list of promotion ids I want to evaluate whether or not a
promotion exists:
//Wrong
$promotion = strstr("25,56","2");
if($promotion){
echo "found";
}else{
echo "not found";
}
//right
function detectPromotion($string,$promotion){
foreach(explode(",",$string) as $promotionToCheck){
echo "checkin ".$promotionToCheck."==".$promotion."<br/>";
if($promotionToCheck==$promotion){
$promotionFound=true;
}
}
return $promotionFound;
}
echo detectPromotion("2,56","2");
http://php.net/manual/en/function.strstr.php