PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<Array Operatorselse>
view the version of this page
Last updated: Tue, 22 Apr 2003

Hoofdstuk 12. Control Structures

Elk PHP script bestaat uit reeksen van statements. Een statement kan een assignment, een functie aanroep, een loop, een conditional statement of zelfs een statement zijn dat niets doet (een empty statement). Statements eindigen gewoonlijk met een puntkomma. Als toevoeging hierop kunnen statements gegroepeerd worden tot een statement-groep door deze te omvatten met accolades. Een statement-groep is een statement op zichzelf. De overige statements zijn beschreven in dit hoofdstuk.

if

De if constructie is ��n van de meest belangrijkste in veel talen, zoals ook in PHP. Het maakt het mogelijk om stukken code conditioneel uit te voeren. PHP heeft een if structuur die gelijk is als die van de taal C.

if (expressie)
    statement

Zoals is beschreven in de sectie over expressies, wordt "expressie" geevalueerd naar zijn "truth" waarde. Als de expressie evalueert tot TRUE, dan zal PHP het statement uitvoeren, en als de expressie evalueert naar FALSE, dan zal het statement worden overgeslagen.

Het volgende voorbeeld zal bijvoorbeeld tonen a is groter dan b indien $a groter is dan $b:

if ($a > $b)
    print "a is groter dan b";

Vaak zul je willen dat er meer dan ��n statement conditioneel wordt uitgevoerd. Natuurlijk hoef je niet elk statement met een if clause te omvatten. In plaats daarvan kun je een meerdere statements tot een statement groep maken. De code in het volgende voorbeeld zal tonen a is groter dan b als $a groter is dan $b, en het zal de waarde van de variabele $a naar $b kopie�ren:

if ($a > $b) {
    print "a is groter dan b";
    $b = $a;
}

If statements kunnen oneindig worden genest binnen andere if statements. Dit geeft je de complete flexibiliteit voor conditionele uitvoering van verschillende delen van je programma.



User Contributed Notes
Control Structures
add a note add a note
lexzeus at mifinca dot com
08-Nov-2000 05:14

function lex1()
{
print "Hello";
return 1;
}
function lex2()
{
print "World";
return 1;
}
if (lex1() || lex2()) {}

it only print "Hello", so lex2() never been executed.

So, u can also write :

if (
   @function1() &&
   @function2() &&
   @function3() &&
   @function4() &&
   @function5()) {}

It will do all functions from 1 to 5 but terminated immediately if one of the function is failed.

LexZEUS

14-Feb-2002 03:20
for beginners like me!
don't forget that if you want a=b, it has to be a==b
for example

<?
$a=2;
$b=2;
if ($a== $b)
echo "that's right!";
?>

and read the manual!

adolfoabegg at hotmail dot com
26-Mar-2002 10:15

You can also use this syntax:
(it worked out for me)

if (conditional):
//sentences
elseif(conditional2):
//sentences
else:
//more sentences
endif;

maurizio at zilli dot com
11-Apr-2002 09:14

You can also use this if/else condition structure
to control an index navigation page statement
and extract partial rows from an array.

// Init to control pointer into the array

$setlimit = 10; // rows limit
$pointer = 0; // this is the start pointer value
$next = $pointer + $setlimit; // increment the pointer
$prev= $next - $setlimit; // decrement the pointer
$total_rows = mysql_num_rows($myrows); // total rows

// You're at the beginning
if (($pointer == 0) && ($total_rows > $setlimit)):

echo"$next >>";

// You're in the middle
elseif ($next < $total_rows):

echo"<< $prev";
echo"$pointer";
echo"$next >>";

// You're in a selection with only one row
elseif (($next == $total_rows) && ($next > $total_rows)):

// You're at the end
else:

echo"<< $prev";

endif;

simon at invalid dot com
20-Aug-2002 07:11

There are something to remind beginners:

if(-1)
echo "(-1 OK) ";
else
echo "(-1 fail) ";

if("")
echo "(\"\" OK) ";
else
echo "(\"\" fail) ";

if(0)
echo "(0 OK) ";
else
echo "(0 fail) ";

//  result:  (-1 OK) ("" fail) (0 fail)

In addition, if you want check if $a,$b and $c are all the same, you should have the condition like that:

if($a==$b && $a==$c) {
   //do somthing;
}
else {
   //do something;
}

Moreover, in (condition1 && condition2), if condition1 is FALSE, then condition2 will not be checked/executed, in the case, if want to executed condition2, use (condition1 & condition2) instead

The case is similar in (condition1 || condition2), if you want to execute condition2 no matter condition1 is TRUE or not, use (condition1 | condition2)

Hope can help you

simon at blueshell.dk
09-Sep-2002 09:30

[Editor's note: It would be better practice to use the ternary operator as argument for the "print" language construct, e.g.:

print ($foo == $bar) ? "The match" : "They don't match";

Same approach can be used for assignment.]

For short if-else's:

if ($foo == $bar) {
print "They match";
} else {
print "They don't match";
}

This can quickly be converted into:

($foo == $bar) ? print "They match" : print "They don't match";

This can be useful if the check's intention can be expressed in matter of a single function, like this.

php dot net at popquizhotshot dot com
10-Dec-2002 01:10

I've noticed the following behaviour:

echo (1==1) ? "true" : "false";
and
echo  "anything here at all" . (1==1) ? "true" : "false";

produce the exact same (unexpected to me) result:

true

"anything here at all" is dropped.

Matt Stanley
13-Feb-2003 04:01

you can use

echo 'anything here at all' , (1==1) ? 'true' : 'false';

instead.  Plus as an extra bonus, its a little faster (for simple text)

16-Feb-2003 10:23
An item that should be added to the Table of Contents on this page:

exit

And for its description (on a new page):

exit�--�Terminate all script execution for this request. (For HTTP requests, this causes the response generated thus far to be sent to the browser.)

Use "return" to terminate the current script only and return to any script that included it (resuming execution at the point after the include).

"exit" can be used immediately following a "require" or "include" to simulate unconditional branching (i.e. "go to") to another script file.

"Exit" is a language construct but is often treated as a function. The parentheses are unnecessary unless a status needs to be returned.

ian at iyates dot com
24-Mar-2003 05:26

In response to LexZEUS:

If you used the same code with | instead of || and & instead of && (as follows)

function lex1()
{
print "Hello";
return 1;
}
function lex2()
{
print "World";
return 1;
}
if (lex1() | lex2()) {}

if (
  @function1() &
  @function2() &
  @function3() &
  @function4() &
  @function5()) {}

All functions would be executed before the final boolean is returned.

Although || and && are more useful (efficient and easy to understand), | and & are normally used when some functions _have_ to be executed even if one fails.

a good example is:
if (isset($a) && $a == 'hello')
   echo $a;

if (isset($b) & $b == 'world')
   echo $b;

while the first 'if' will always be okay, the second will return an error if $b had not been set as it will still compare $b to 'world' (which should return 'false' and a warning)

kriek at jonkriek dot com
29-Mar-2003 02:06

It should be noted that in MOST cases it is fifteen percent faster to use switch/case/break instead of if/elseif/else. Of course this depends on your application and individual code results do very.

<?php
   if ($_GET['page']) {
       $page = $page . '.php';
     if (file_exists($page)) {
           include($page);
       }
   } else {
       include('welcome.php');
   }
   if ($_GET['auc']) {
       $auc = $auc . '.html';
       if (file_exists($auc)) {
           include($auc);
       }
  } else {
       include('welcome.html');
   }
?>

Storm
04-May-2003 12:16

Although the alternate syntax is nice, I myself prefer to use a simple function:

function iif ($statement,$true_return,$false_return) {
   if ($statement == false) {
       return $false_return;
  } else {
       return $true_return;
   }
}

Works great for me...

$one = iif (isset($one),$one,'one');
$two = iif (isset($two),$two,'two');
$three = iif (isset($three),$three,'three');

:D

armond A.T technoREM0VEmonk d0t com
14-May-2003 06:02

From my tests, some more complex if() statements may not have desired results.

Take for instance,
$a = 79;
$b = 82;
$c = 40;
if($c == ($a || $b)) { ... }

You would think that would be stating:
"If $c equals $a or $b"
And would return false, but think again.

I have an idea of whats going on here-its equating it like a matematical equasion, and we follow the EPMDAS order.

I haven't found a workaround, so for now we're stuck to:
if($c == $a || $c == $b) { .. }

Armond Carroll

add a note add a note

<Array Operatorselse>
 Last updated: Tue, 22 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Sat May 24 21:09:36 2003 CEST