-
if...else...elseif 语句
if (条件) {
// 条件为 true 时执行的代码;
} elseif (condition) {
//条件为 true 时执行的代码;
} else {
//条件为 false 时执行的代码;
}
<?php
$t=date("H");
if ($t<"10") {
echo "Have a good morning!";
} elseif ($t<"20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
-
switch 语句
工作原理:
- 对表达式(通常是变量)进行一次计算
- 把表达式的值与结构中 case 的值进行比较
- 如果存在匹配,则执行与 case 关联的代码
- 代码执行后,break 语句阻止代码跳入下一个 case 中继续执行
- 如果没有 case 为真,则使用 default 语句
switch (expression)
{
case label1:
//expression = label1 时执行的代码 ;
break;
case label2:
//expression = label2 时执行的代码 ;
break;
default:
//表达式的值不等于 label1 及 label2 时执行的代码;
}
<?php
$favfruit="orange";
switch ($favfruit) {
case "apple":
echo "Your favorite fruit is apple!";
break;
case "banana":
echo "Your favorite fruit is banana!";
break;
case "orange":
echo "Your favorite fruit is orange!";
break;
default:
echo "Your favorite fruit is neither apple, banana, or orange!";
}
?>
- while 循环
- do...while 循环
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
?>
</body>
</html>
输出
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
- for 循环
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br>";
}
?>
输出结果:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
- foreach 循环
语法:
foreach ($array as $value)
{
要执行代码;
}
<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br>";
}
?>
输出:
one
two
three
- 数组
- 数值数组 - 带有数字 ID 键的数组
- 关联数组 - 带有指定的键的数组,每个键关联一个值
- 多维数组 - 包含一个或多个数组的数组
遍历关联数组
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
运行结果:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
- 数组排序
- sort() - 对数组进行升序排列
- rsort() - 对数组进行降序排列
- asort() - 根据关联数组的值,对数组进行升序排列
- ksort() - 根据关联数组的键,对数组进行升序排列
- arsort() - 根据关联数组的值,对数组进行降序排列
- krsort() - 根据关联数组的键,对数组进行降序排列
- 超级全局变量