if( condition ) instruction_to_run_when_condition_is_true; else instruction_to_run_when_condition_is_false;In the short form of the if statement the else part can be skipped. In this case PHP interpreter just checks the condition and executes the given instruction only if the condition is true. If the condition isn't met then the code will be completely ignored, and won't be executed by PHP at all. It will then jump to the next line. Here is a short example, in which the program check that the amount of money paid is greater than 25 dollars if it's so, then it will add "sir" before the name. Otherwise, it'll print the greeting without "sir".
This if statement will execute the only one next instruction after the parenthesis if you need to run several instructions you have to use curly brackets to combine them. Everything inside curly brackets block is considered by PHP as one big instruction.
if( $guess > $number ) {
echo "Guess is too high";
echo "<br>I was thinking of $number, you don't ";
}
If you want to execute one set of statements if a condition is true, and another set if the condition is false you can use the complete form of the if statement which includes else:
if( $age>21 AND $license=="on" ) {
echo "Your car hire has been accepted.";
}
else{
echo("Unfortunately we can not accept you.")
}
Sometimes you need to check more complicated conditions and farther conditions can depend on the first condition being true or not. In this case elseif statement can help:
if( $age>21 && $license=="on" ){
echo("Your car hire has been accepted.");
}
elseif( $age>18 AND $license=="on" ){
echo "Your car hire has been accepted, subject to you providing the name of guarantor.":
}
else{
echo "Unfortunately we can't hire a car to you.";
}
As a condition of the if statement we can use any Boolean expression.
$bool_exp = $age > 21;We can use any of the comparison operators from the table below.
More complicated Boolean expression can include a combinations of simpler Boolean expression. For example, if we need to make sure that both conditions are true age is greater than 21 and there is a drivers license, then we can create a more difficult expression using logical operator and:
$serve_beer = ($age > 21) && $is_license;All Boolean operators we can use to combine simple Boolean expression into difficult ones are in the table below:
| Comparison operators | |
| < | less than |
| > | greater than |
| <= | less than or equal |
| >= | greater than or equal |
| != | not equal |
| <> | not equal |
| == | equality operator |
| === | recently introduced a new version of equality operator. This returns true only if the values are equal and the data types of the variable are also equal. |
| Logical operators | |
| AND | logical multiplication, returns true only if both (left and right) operands are true |
| && | same as above, but takes precedence over its textual alternative |
| OR | logical addition, returns true if at least one of the operands is true |
| || | same as above, but takes precedence over its textual alternative |
| ! | not operator. Returns true only if the operand following the exclamation mark is false. Please note that you can not use word NOT for this operator. |
The switch statement performs a similar function to a multiple if-elseif statement. However it is much easier to read and allows us to leave out nearly all of the irritating braces. The general syntax for the switch statement is:
switch( expression ){
case choice_1:
choice_1_statements;
break;
case choice_2:
choice_2_statements;
break;
case choice_3:
choice_3_statements;
break;
...
case choice_n:
choice_n_statements;
break;
default:
default_statements;
}
It works the following way:
switch( $Grade ){
case $Grade > 70:
echo "You got an A.";
break;
case $Grade > 60:
echo "You got a B.";
break;
case $Grade > 50:
echo "You got a C.";
break;
case $Grade > 40:
echo "You got a D.";
break;
case $Grade > 25:
echo "You got an E--.";
break;
default:
echo("Sorry pal");
}
Please note that we use break statement in our switch statement. When PHP encounters break, it stops what it's doing, drops out of the whole switch structure and picks up the programming statement after the closing brace. Actually, syntax of the switch statement does not require break in it, but if you skip it all instructions after the right case will be executed, including ones in other cases.
The switch statement also introduces an interesting little shorthand: If you just supply a value next to the case keyword, then it automatically checks if the variable you supplied in the switch parentheses for equality with the value next to case, whether numerical or textual.
condition ? value_one : value_twoIf the condition is true it returns value_one, otherwise it returns value_two. It is very convenient in output strings. For instance, example with the "sir" we can rewrite using the question mark operator:
echo "Hello, " . ($amount>25 ? "sir" : "" ) . "Daniel.";In this code
while loop is probably the simplest one, and it's also similar to if statement. The general form of this loop is:
while( execute_condition )
{
instructions_to_repeat;
}
Like the if statement, it checks the result of the condition. Depending on whether the condition is true or false,
the section of the code after the conditional statement is executed. After the instructions inside the loop are executed,
the condition at the top is tested again, and the code might be executed again, and so on.
while( $ShoppingTotal <= $CreditLimit )
{
echo "Let's buy some more!<br>";
$ShoppingTotal = $ShoppingTotal + $OneMoreItemPrice;
}
echo "Now I need to have credit limit increased.";
This while loop will be executed an number of times (which we don't know) until the total price exceeds the
credit limit. Using while construction we can repeat some code a certain amount of times:
This code prints a table with one column and 9 rows and makes all odd rows blue.
do
{
instructions_to_repeat;
}
while( repeat_condition );
Please notice the semicolon at the end of the loop. The same example can be rewritten using do-while loop:
echo "<table border=1>\n";
do{
if( empty($i) )
$i=1;
echo " <tr><td width=100px" . ($i%2==1 ? " style='background-color:blue;'":"") . "> </td></tr>\n";
$i++;
}while( $i < 10 );
echo "</table>\n";
for( initialization; testing; changes )
{
instructions_to_repeat
}
In the initialization part we usually set a loop counter (a variable which is used to count the amount of times we have
been around the loop). In the testing part we usually test if the loop counter exceeded a given amount of iterations.
The third part of the condition we specify instructions which should be executed at the end of each loop, it's usually
used to increment or decrement the loop counter. Here is a typical for loop:
for($i=0; $i<10; $i++)
{
echo "The name is $Name[$i]<br>";
}
This code prints ten elements of an array $Name.
None of these three parts of the condition is actually required. That is, we can rewrite the previous loop like this:
$i = 0;
for(;$i<10;)
{
echo "The name is $Name[$i]<br>";
$i++;
}
making it behave exactly like while loop, or even like that:
$i = 0;
for(;;)
{
if( $i >= 10 ) break;
echo "The name is $Name[$i]<br>";
$i++;
}
Please notice that the keyword break we have seen in the switch statement does the same
job here getting us out of the loop.
Here is a small example that uses two for loops (nested) to create a chess board: