0

The question is from a statement from a piece of code from here (the last PHP program on the page) The statement is:

if (stristr($q, substr($name,0,$len))) {...}

But according to the manual, the return type of stristr() is string. It returns a string, not a bool, so how can we use it in an if statement?

Solace
  • 8,612
  • 22
  • 95
  • 183

2 Answers2

3

PHP, like most programming languages evaluates the conditional expression (the code inside an if statement) to a boolean expression:

if (123)
    echo '123 is true';

This will echo the text because, when it comes to ints, everything except 0 is true (or truthy as it is also known).
You can check the official documentation here to get a detailed overview of what types/values evaluate to true and which to false.

Of course, in the case of strstr and stristr, when no substring is found, the function will actually return false, and so a type and value check of the return value is not uncommon:

if (stristr($string, 'needle') !== false)
    echo 'The needle was found';
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • 2
    @JuanMendes: in C, any non-zero and non-NULL value is true: `if (-1) printf("%d is true\n", -1);` works just as well – Elias Van Ootegem Sep 21 '14 at 13:42
  • Thank you very much, especially for the link to the documentation, as this confuses me quite often. – Solace Sep 21 '14 at 13:43
  • @Zarah: You're welcome. Would you mind awfully marking one of the answers as accepted, seeing as your question was answered? – Elias Van Ootegem Sep 21 '14 at 13:53
  • @EliasVanOotegem I could not accept an answer in the first few minutes. It said that I can accept an answer in X minutes whenever I tried. I accepted it as soon as I could. – Solace Sep 21 '14 at 14:20
1

From the link you posted

Return Values

Returns the matched substring. If needle is not found, returns FALSE.

When it returns a string, PHP considers non-empty strings to be truthy when used in an if statement

Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • 1
    nit-pick, but PHP's truth tables are quite messed up: `if ("0" == false)` will evaluate to true. And worst of all `if ("php" == 0)` is true, too, just as `if ("php" == true)` is true... :-S – Elias Van Ootegem Sep 21 '14 at 13:53