开发者

Regarding if statements in PHP

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 specifica开发者_Go百科lly. Can anybody shed some light on this?


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


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.


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.


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.


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.


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) { ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜