Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Language Reference : Control Structures

Chapter 7. Control Structures

Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.

if

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

if (expr)
   statement

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.

The following example would display a is bigger than b if $a is bigger than $b:

<?php
if ($a > $b)
   echo
"a is bigger than b";
?>

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

<?php
if ($a > $b) {
   echo
"a is bigger than b";
   
$b = $a;
}
?>

If statements can be nested indefinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.

Code Examples / Notes » language.control_structures

wintermute

Sinured: You can do the same thing with logical OR; if the first test is true, the second will never be executed.
<?PHP
if (empty($user_id) || in_array($user_id, $banned_list))
{
exit();
}
?>


abu_hurayrah

Regarding lamfeust's example:
   Just a note about initializing variable
   <?php
   if($foo=false)
     print("true");
   else
     print("false");

   // this print on screen false
   ?>
This will print out "false" due to the expression "$foo=false" returning the value of the assignment - boolean false, in this case.
I'm not sure what, exactly, that had to do with initialization.


christopher dot metz

in the two previous examples, both are correct.
for $foo = false, you're assigning the value while operating in the condition, so its just like:
$foo = false;
if( $foo )
  print( 'a' );
else
  print( 'b' );
....returns 'b';
for $foo == false, it will return true or false based on if $foo equals false or true, respectively.


roan dot kattouw

In response to Niels: The ANSI C standard also dictates this laziness .

petter no-spam

if($alfa > $beta) {
  $alfa = $some;
} else {
  $alfa = $thing;
}
Another method:
$alfa = ( $alfa > $beta )? $some : $thing;


fteng1

Here's a lazy way of doing an comparison where multiple conditions equal the same result using arrays.
if (in_array($year,array(1948, 1960, 1972, 1984, 1996, 2008)))
echo "Rat";
elseif (in_array($year,array(1949, 1961, 1973, 1985, 1997, 2009)))
echo "Ox";
elseif (in_array($year,array(1950, 1962, 1974, 1986, 1998, 2010)))
echo "Tiger";
elseif (in_array($year,array(1951, 1963, 1975, 1987, 1999, 2011)))
echo "Rabbit";
elseif (in_array($year,array(1952, 1964, 1976, 1988, 2000, 2012)))
echo "Dragon";
elseif (in_array($year,array(1941, 1953, 1965, 1977, 1989, 2001)))
echo "Snake";
elseif (in_array($year,array(1942, 1954, 1966, 1978, 1990, 2002)))
echo "Horse";
elseif (in_array($year,array(1943, 1955, 1967, 1979, 1991, 2003)))
echo "Lamb";
elseif (in_array($year,array(1944, 1956, 1968, 1980, 1992, 2004)))
echo "Monkey";
elseif (in_array($year,array(1945, 1957, 1969, 1981, 1993, 2005)))
echo "Rooster";
elseif (in_array($year,array(1946, 1958, 1970, 1982, 1994, 2006)))
echo "Dog";
elseif (in_array($year,array(1947, 1959, 1971, 1983, 1995, 2007)))
echo "Boar";


dougnoel

Further response to Niels:
It's not laziness, it's optimization.  It saves CPUs cycles.  However, it's good to know, as it allows you to optimize your code when writing.  For example, when determining if someone has permissions to delete an object, you can do something like the following:
if ($is_admin && $has_delete_permissions)
If only an admin can have those permissions, there's no need to check for the permissions if the user is not an admin.


niels dot laukens

For the people that know C: php is lazy when evaluating expressions. That is, as soon as it knows the outcome, it'll stop processing.
<?php
if ( FALSE && some_function() )
   echo "something";
// some_function() will not be called, since php knows that it will never have to execute the if-block
?>
This comes in nice in situations like this:
<?php
if ( file_exists($filename) && filemtime($filename) > time() )
   do_something();
// filemtime will never give an file-not-found-error, since php will stop parsing as soon as file_exists returns FALSE
?>


simplyduh

dougnoel, you are wrong recarding optimization:
> if ($is_admin && $has_delete_permissions)
> If only an admin can have those permissions, there's no
> need to check for the permissions if the user is not an admin.
Duh, both are booleans in the above case, and its obvious that
checking one boolean is better than checking 2.
if ($has_delete_permissions) would work better :)


sinured

As mentioned below, PHP stops evaluating expressions as soon as the result is clear. So a nice shortcut for if-statements is logical AND -- if the left expression is false, then the right expression can’t possibly change the result anymore, so it’s not executed.
<?php
/* defines MYAPP_DIR if not already defined */
if (!defined('MYAPP_DIR')) {
define('MYAPP_DIR', dirname(getcwd()));
}
/* the same */
!defined('MYAPP_DIR') && define('MYAPP_DIR', dirname(getcwd()));
?>


mongoose643

@simplyduh
>Duh, both are booleans in the above case, and its obvious
>that checking one boolean is better than checking 2.
>if ($has_delete_permissions) would work better :)
I read dougnoel's post. He was providing an example of a BAD example. The last line in his post suggests that you NOT check for both - only the admin. So actually what he meant to check for is whether or not they are an admin. If so then they automatically have delete permissions - therefore it may be possible that no variable named "$has_delete_permissions" exists. The resulting statement would be as follows:
if($is_admin)
{
   //Statements to delete stuff go here.
}


captainf

@mongoose643
dougnoel was actually trying to provide a good example of how the if function automatically evaluates to false and goes no further if the first condition in an if expression fails can be used to optimize a script. In his example not everyone is an admin, and not all admins can delete. In his script it is an optimized failsafe to check if someone is an admin and has delete permissions while not wasting script time.


jupiter

// assigning a variable inside an IF conditional does assign the value,
// then if it evaluates to true, continues to the true statement group
<?php
$a = array(1, 2, ' ', true, 0, '', false, array());
foreach ($a as $b) {
if ($c[] = $b) {
echo 'true, ';
} else {
echo 'false, ';
}
}
print_r($c);
/*  RETURNS
true, true, true, true, false, false, false, false
Array
(
   [0] => 1  // integer
   [1] => 2  // integer
   [2] =>    // a single space
   [3] => 1  // boolean true
   [4] => 0  // integer
   [5] =>    // nothing
   [6] =>    // nothing
[7] => array()
)
*/
?>
// Notice $c[4] and $c[7] are assigned values, but then evaluate to false


28-may-2006 09:07

$foo=false will never work as it is tha assign operator.
$foo == false is required


Change Language


Follow Navioo On Twitter
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects (PHP 4)
Classes and Objects (PHP 5)
Exceptions
References Explained
eXTReMe Tracker