0

A newbie question. Here is a function and an if statement.

<?php

    function test(){
        echo "somedata";    
    }

    if(test())      

?>

This code produces: somedata

According to documentation an if expression should only return TRUE or FALSE, but apart of it, function runs. Why it happens?

trincot
  • 317,000
  • 35
  • 244
  • 286
Leonid
  • 55
  • 2
  • 10

1 Answers1

3

PHP evaluates the if expression in order to know if the epression yields a truthy value or not. There is no other way to find out than to execute the functions that appear in the expression.

In this example it is very clear:

 if (sqrt(4) > 1)
 

PHP must of course call the function sqrt, except that in this case it is a function without side-effects, while your function test also performs an echo. Secondly, it returns a value, while test doesn't. But that PHP can only find out by executing the function.

Note that the expression can in general return anything, but PHP has rules to what it considers truthy or falsy:

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

In case a function runs without executing a return statement, the returned value is null, so the if condition will be falsy according to the above rules.

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286
  • It's worth noting that `echo "somedata"` is completely irrelevant here. The function can have empty body as well - as long as it got no `return` it completely does not matter what the function does. – Marcin Orlowski Jun 01 '16 at 18:13
  • @MarcinOrlowski, except of course if the function performs an `exit()` (or the equivalent `die()`), or throws an exception. There some [other creative ways](http://stackoverflow.com/questions/21457734/how-to-stop-php-code-execution) to break the normal execution flow. – trincot Jun 01 '16 at 18:21
  • In such case `if()` wont be evaluated so I'd say it still does not matter as we assume normal flow. Turning machine off or killing PHP process may also affect this `if()` when timed accurately, but this is not we shall bother. – Marcin Orlowski Jun 01 '16 at 20:06