What does it mean php uses strstr as a boolean check?

For example, given code:

if(strstr($key, ".")){
    // do something
}

      

strstr returns a string, how can it be used as boolean? How will it turn around or turn out to be false?

+3


source to share


4 answers


Referring to the PHP doc :

Returns part of the string, or FALSE if no needle was found.



So the boolean check is basically whether or not a substring is found ( .

in this case).

Any other value this function can return is a non-empty string, which will be true-valued (see this doc entry .)

+1


source


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 within another string. This function returns the rest of the string (from the point of match) or FALSE if no string to search is found.



    strstr(string,search)

      

string

----> Required. Specifies the search string

search

----> Required. Specifies the search string. If this parameter is a number, it will look for a character that matches the ASCII value of the number.

+2


source


It's simple: in an if statement, when we have an empty value, such as 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 the 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
}

      

+1


source


The return 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) can also be used because no string will be selected for bool (true)

echo is_bool('test') ? 'true' : 'false'; //false

      

+1


source







All Articles