章 16. 流程控制

任何 PHP 脚本都是由一系列语句构成的。一条语句可以是一个赋值语句,一个函数调用,一个循环,甚至一个什么也不做的(空语句)条件语句。语句通常以分号结束。此外,还可以用花括号将一组语句封装成一个语句组。语句组本身可以当作是一行语句。本章讲述了各种语句类型。

if

if 结构是很多语言包括 PHP 在内最重要的特性之一,它允许按照条件执行代码片段。PHP 的 if 结构和 C 语言相似:

<?php
if (expression)
    statement
?>

如同在表达式一章中定义的,expression 按照布尔求值。如果 expression 的值为 TRUE,PHP 将执行 statement,如果值为 FALSE - 将忽略 statement。有关哪些值被视为 FALSE 的更多信息参见转换为布尔值一节。

如果 $a 大于 $b,则以下例子将显示 a is bigger than b

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

经常需要按照条件执行不止一条语句,当然并不需要给每条语句都加上一个 if 子句。可以将这些语句放入语句组中。例如,如果 $a 大于 $b,以下代码将显示 a is bigger than b 并且将 $a 的值赋给 $b

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

if 语句可以无限层地嵌套在其它 if 语句中,这给程序的不同部分的条件执行提供了充分的弹性。


add a note add a note User Contributed Notes
29-May-2006 04:07
$foo=false will never work as it is tha assign operator.

$foo == false is required
abu_hurayrah at hidayahonline dot org
25-May-2006 04:42
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.
dougnoel
06-May-2006 09:29
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.
roan dot kattouw at home dot nl
09-Dec-2005 08:49
In response to Niels: The ANSI C standard also dictates this laziness .
niels dot laukens at tijd dot com
26-Dec-2004 11:49
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
?>