[PHP 4, PHP 5, PHP 7, PHP 8]
The if
construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if
structure that is similar to that of C:
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. More information about what values evaluate to false
can be found in the 'Converting to boolean' section.
The following example would display a is bigger than b if $a is bigger than $b:
Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if
clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:
If
statements can be nested infinitely within other if
statements, which provides you with complete flexibility for conditional execution of the various parts of your program.
robk ¶
9 years ago
easy way to execute conditional html / javascript / css / other language code with php if else:
html code to run if condition is true
html code to run if condition is false
grawity at gmail dot com ¶
14 years ago
re: #80305
Again useful for newbies:
if you need to compare a variable with a value, instead of doing
do
this way, if you forget a =, it will become
and PHP will report an error.
techguy14 at gmail dot com ¶
11 years ago
You can have 'nested' if statements withing a single if statement, using additional parenthesis.
For example, instead of having:
You could just simply do this:
Hope this helps!
Christian L. ¶
11 years ago
An other way for controls is the ternary operator [see Comparison Operators] that can be used as follows:
Parentheses can be left out in all examples above.
cole dot trumbo at nospamthnx dot gmail dot com ¶
5 years ago
Any variables defined inside the if block will be available outside the block. Remember that the if doesn't have its own scope.
It will print 'Hello to all people!'
On the other hand, this will have no output:
Donny Nyamweya ¶
11 years ago
In addition to the traditional syntax for if [condition] action;
I am fond of the ternary operator that does the same thing, but with fewer words and code to type:
[condition ? action_if_true: action_if_false;]
example
[x > y? 'Passed the test' : 'Failed the test']