Control Structures in PHP

From Free Knowledge Base- The DUCK Project: information for everyone
(Redirected from If Construct in PHP)
Jump to: navigation, search

if

When compared to the C programming language, PHP is "lazy" as it will terminate processing of the if routing as soon as it determines the outcome.

 if ( $comp == "open" ) {
 if (!empty($cfgRelation['relation'])) {
 if ($have_rel) {
 if (typeof(window.print) != 'undefined') {
 if (!empty($tbl_group) && !$cfg['ShowTooltipAliasTB']) {
 if (empty($var)) {
 if (isset($var)) {

switch

Below is an IF struction and a SWITCH structure that both do the same thing.  
-------------------------------------------------------------------------------
<?php
if ($i == 0) {
   echo "i equals 0";
} elseif ($i == 1) {
   echo "i equals 1";
} elseif ($i == 2) {
   echo "i equals 2";
} 
-------------------------------------------------------------------------------
switch ($i) {
case 0:
   echo "i equals 0";
   break;
case 1:
   echo "i equals 1";
   break;
case 2:
   echo "i equals 2";
   break;
}
?>

More examples using switch / case.

<?php
switch ($i) {
case "apple":
   echo "i is apple";
   break;
case "bar":
   echo "i is bar";
   break;
case "cake":
   echo "i is cake";
   break;
}
?>


<?php
switch ($i) {
case 0:
   echo "i equals 0";
   break;
case 1:
   echo "i equals 1";
   break;
case 2:
   echo "i equals 2";
   break;
default:
   echo "i is not equal to 0, 1 or 2";
}
?>