超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<数组运算符else>
Last updated: Fri, 22 Jun 2007

章 16. 流程控制

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

if

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

if (expr)
    statement

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

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

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

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

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

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




add a note add a note User Contributed Notes
流程控制
molotov at molotov dot eu dot org
30-Sep-2003 12:25
You definitely can write a simple control structure like this:
<?php
if ($var > 5)
{
   $answ = $var1;
}
else
{
   $answ = $var2;
}
?>

But there is a much shorter way:

<?php
$answ = ( $var > 5 ? $var1 : $var2 );
/* $result = ( $expression ? $return_if_true : $return_if_false ) */
?>
Athon Solo
05-Sep-2003 03:41
If you want to check for multiple conditions you can do it in atleast 2 ways:

1. Nested if statements:
<?php

 if ($var1 == $var2) {
   if ($var1 != $var3) {
     echo $var1 ." = ". $var2 ." != ". $var3;
   }
 }
?>

2. All in one line:
<?php

 if (($var1 == $var2) AND ($var1 != $var3)) {
   echo $var1 ." = ". $var2 ." != ". $var3;
}
?>

Note: you can also use the 'OR' keyword between conditions.
You can have as many conditions as you want.
For full details on 'operators' like AND and OR, please see http://www.php.net/language.operators
maurizio at zilli dot com
12-Apr-2002 02: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;

<数组运算符else>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22