3

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?

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
  • 2
    `Returns the portion of string, or FALSE if needle is not found.` So, if the result is not FALSE, it means it's TRUE (as in truish, though, not as in boolean.) Basically is a check for a NON-FALSE value – Damien Pirsy Feb 03 '13 at 20:35
  • So returns if there is no "." in this situation? Interesting.. Is this documented? Because I thought this method returned a string not a boolean? – Koray Tugay Feb 03 '13 at 20:35

4 Answers4

2

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.

Naveen Shan
  • 9,192
  • 3
  • 29
  • 43
echo_Me
  • 37,078
  • 5
  • 58
  • 78
1

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.)

Sirko
  • 72,589
  • 19
  • 149
  • 183
1

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
}
John Skoumbourdis
  • 3,041
  • 28
  • 34
1

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