2

I've seen some PHP statements that go something like

 if($variable) {} or
 if(function()) {} (if statements that don't compare two variables)

and I know they roughly mean if a function executes or if this variable exists but I can't seem to find any information on how they work specifically. Can anybody shed some light on this?

Austin Gayler
  • 4,038
  • 8
  • 37
  • 60

6 Answers6

7

if(function()) {} means if the function function's return value is true or true-like then the block will execute.

2

If a variable is equal to a number which is not zero, that's considered as true. as well as if the function returns a positive/negative number which is different from 0.

logicbloke
  • 139
  • 3
  • 13
2

From the PHP manual:

if (expr) statement

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.

So, if a function successfully runs (true) or a variable exists (true) the if statement will continue. Otherwise it will be ignored.

steve
  • 576
  • 1
  • 5
  • 12
1

The if statements determine whether the given variable is true or a given function returns true. A variable is considered "true" if it isn't null, false, 0, or (perhaps) an empty string.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
1

When PHP evaluates if statements, it is determining whether or not the contents are true. It considers anything other than 0 to be true, and 0 to be false. This means you can put a function in there that returns anything and based on that it will determine whether or not to execute the contents of the if block.

1

something that may help. You are probably thinking of something like if ($variable < 10), or if ($variable == 'some value'). Just like +, -, /, *, and % these are operators. 1 + 3 returns a value of 4 which is used in the rest of a standard statement. 1 < 3 returns a value of false which is used in the rest of the statement. the if-method accepts a boolean parameter, and executes code if that boolean parameter is true.

notice that:

if (1 < 3) { ... }

is the same as

$myComparison = 1 < 3;
if ($myComparison) { ... }
Assimilater
  • 944
  • 14
  • 33