function StringCount($searchstring, $findstring)
{
return (strpos($searchstring, $findstring) === false ? 0 : count(split($findstring, $searchstring)) - 1);
}
it returns number of ocourances of substring in string, but why not just use count?
What means === false ? 0 :
i mean how this called its not if or case is there way to call this type of writing?
4 Answers 4
http://www.php.net/manual/en/language.operators.comparison.php - about ===
http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary - about (expr1) ? (expr2) : (expr3)
But, i think it is better to use substr_count() ( http://www.php.net/manual/en/function.substr-count.php ) in this function
Comments
This is a type of ternary operator (meaning it takes 3 operands), and is a short form of the if then else clause.
a ? b : c can be expanded as:
if(a)
{
b
}
else
{
c
}
So in essence it is something like this:
$strPos;
if (($searchstring, $findstring) === false)
{
$strPos=0
}
else
{
$strPos=count(split($findstring, $searchstring))
}
return strpos($strPos-1);
5 Comments
x ? y:zand if(x) { y } else { y } are not exactly the same thing. Yes, it's easier to grasp for beginners when explained this way but no, it's not the same ;-)b and c are expressions, not statements, and the whole result is almost always assigned to something. (If it's not assigned, many would argue the operator is being abused and should be rewritten as an if/else statement.) More correct would be to say that x = (a ? b : c) is equivalent to if (a) x = b; else x = c;.$previous_comment =~ s:assigned:assigned/returned/passed:g;Because strpos returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "".
A good example is that StringCount("stackoverflow","stack") will return 0 if
function StringCount($searchstring, $findstring)
{
return (strpos($searchstring, $findstring) == false ? 0 : count(split($findstring, $searchstring)) - 1);
}
Comments
It's a ternary condition
If strpos($searchstring, $findstring) is false, then 0, else count(split($findstring, $searchstring)) - 1
So if $findstring is NOT found in $searchstring, return 0
The reason you need 3 = for that false statement is strpos returns an integer of where the needle was found in the haystack. Buy using === you get the boolean.