Explain this function syntax
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 th开发者_如何学运维is type of writing?
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
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);
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);
}
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.
精彩评论