All pastes #215012 Raw Edit

Untitled

public text v1 · immutable
#215012 ·published 2006-10-22 10:04 UTC
rendered paste body
Control structure s

It's very important to know how to check if a condition is true or not, so we will now speak about that. The most basic control structure is if(). It's sintax is:

Codi:

<?PHP
  if(true) {
    echo 'True';
  } else {
    echo 'False';
  }
?>


You can check variables and strings using:

Codi:

a === b  // a is equal to b
a !== b  // a is different to b
a < b     // a is smaller than b
a > b    // a is bigger than b


Here's an example (that's a simple version of that about we spoke at the end of the last chapter):

Codi:

<?PHP
  $var = $HTTP_GET_VARS['var'];
  if($var === 'news') {
     include('./news.inc');
  } else {
    include('./home.inc');
  }
?>


There's also elseif, which checks another condition if the last one was false. I think with that example it's clear enought (and if you don't understan d it you should read again the previous chapters):

Codi:

<?PHP
  $var = $HTTP_GET_VARS['var'];

  if($var === 'news') {
     include('./news.inc');
  } elseif($var === 'downloads') {
     include('./downloads.inc');
  } elseif($var === 'products') {
     include('./products.inc');
  } else {
    include('./home.inc');
  }
?>


If you want to check for many coditions you can use the && (AND) and the || (OR) operators .

Codi:

<?PHP
  if($a === $b && $c === $d) {
     echo $a.' is equal to '.$b.' and '.$c.' is equal to '.$D';
  } elseif($a === $b && $c === $d) {
     echo 'Variable A is equal to variable B, or variable C is equal to variable D';
  } else {
     echo 'None of them matches.';
  }
?>


In long condition s you can also use brackets:

Codi:

<?PHP
  if($a === $b && ($c === '5' || $c === '10') {
    echo 'Variable $a is equal to variable $b. Variable $c can be equal to 5 or 10.';
  }
?>



Short form

If has also a short form:

Codi:

<?PHP
   ($var1 === $var2) ? echo 'true' : echo 'false';
?>


Instead of if(statement) you just write (statement), followed by a question mark (?). Then you can do an operation (for example, print some text), but don't put the semi-colon (Ginyar after it! Then use : instead of else, do there another operation and end the if with semi-colon (Ginyar.

If you want (for example) to print only some text if a condition is true, but not if it is false, you can use:

Codi:

if(5 < 3) echo '5 is smaller than 3';


... without { and }. The if will end with the first semi-colon (Ginyar.