if/else

The if/else pair is a way to use a Boolean expression to determine which block of code to execute.

Example:
The example below will print the values of $x and $y in order. Put this code on a test page, then give x different values in the URL: test.php?x=5&y=9 or test.php?x=abc&y=a
<?php
if($x<$y) echo $x.' '.$y;
else echo $y.' '.$x; ?>
Use your imagination: try different values for $x and $y, use upped and lower case, negative and positive and even combine letters and numbers such as test.php?x=5&y=abc

Blocks

To execute more than one statement for the true or false code, a pair of braces encloses the block. It is a good practice to label each } with a comment and use indentation for the statements inside the block.
Anywhere one statement is allowed, a block can be used to group statements. A block will also be used for statements within a loop, and other situations.

Because forgetting the curly braces can cause many errors, some programmers always put in the curly braces, even if there is only one statement in the block: TEST PAGE

<?php
if($x<$y) {
  echo $x.' '.$y;
} //true
else {
  echo $y.' '.$x;
} //false
?>

INDEX, Boolean Values, if/else, Summary, Compound Conditions: AND && and OR ||, SWitch
Next lesson: Important InformationMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

if/else