For example given code:
if(strstr($key, ".")){
// do something
}
strstr returns a string, how can it be used as boolean? How does it turn true or false?
For example given code:
if(strstr($key, ".")){
// do something
}
strstr returns a string, how can it be used as boolean? How does it turn true or false?
here is an example
<?php
$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>
definition:
The strstr()
function searches for the first occurrence of a string inside another string.
This function returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.
strstr(string,search)
string
----> Required. Specifies the string to search
search
----> Required. Specifies the string to search for. If this parameter is a number, it will search for the character matching the ASCII value of the number.
Citing from the PHP docu:
Returns the portion of string, or FALSE if needle is not found.
So the boolean check is basically, whether the substring (the .
in this case) is found at all.
Any other value this function can return is a non-empty string, which will be evaluated to truthy (See this entry in docu.)
This is simple: in an if statement , when we have a value that is empty for example a non empty string , this is true. For example:
if("test") { //this is true
}
$value = "test";
if($value) { //this is true
}
$value = 3;
if($value) { //this is true
}
On the other hand when you have an empty variable then in if statement it acts like false. For example:
$var = 0;
if($var) { //this is false
}
$var = false;
if($var) { //this is false
}
$var = "";
if($var) { //this is false
}
So in your case you have:
$key = "test.com"
$val = strstr($key, "."); //Return ".com"
if ($val) { //This is not a non empty string so it is true
}
$key = "justtest"
$val = strstr($key, "."); //Return boolean false so it is false
if ($val) { //This is returning boolean false
}
The return of strstr is either boolean (false) or string, then
$strstr = strstr($key, '.');
if(is_string($strstr)){
echo 'is found';
}
or
if($strstr === false){
echo 'not found';
}
Note: is_bool($strtsr) also can be used because the string will not be casted to bool (true)
echo is_bool('test') ? 'true' : 'false'; //false