Reputation: 4356
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?
Upvotes: 2
Views: 1415
Reputation: 138
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.
Upvotes: 2
Reputation: 964
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) { ... }
Upvotes: 1
Reputation:
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.
Upvotes: 1
Reputation: 576
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.
Upvotes: 2
Reputation: 32878
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.
Upvotes: 1
Reputation:
if(function()) {}
means if the function function's return value is true or true-like then the block will execute.
Upvotes: 7