流程控制语句 同js
<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } $t=date("H"); if ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } $t=date("H"); if ($t<"10") { echo "Have a good morning!"; } else if ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } $favcolor="red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, or green!"; } //循环 $i=1; while($i<=5) { echo "The number is " . $i . ""; $i++; } $i=1; do { $i++; echo "The number is " . $i . "
"; } while ($i<=5); for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "
"; } $x=array("one","two","three"); foreach ($x as $value) { echo $value . "
"; } ?>
数组
<?php $cars=array("Volvo","BMW","Toyota"); //数组定义 数值数组 echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; //访问数组元素 //数组长度count() $cars=array("Volvo","BMW","Toyota"); echo count($cars); //count() 函数用于返回数组的长度 //遍历数值数组 $cars=array("Volvo","BMW","Toyota"); $arrlength=count($cars); for($x=0;$x<$arrlength;$x++) { echo $cars[$x]; echo ""; } $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");//定义关联数组 echo "Peter is " . $age['Peter'] . " years old."; //遍历关联数组 $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "
"; } ?>
数组排序
PHP - 数组排序函数
sort() - 对数组进行升序排列
rsort() - 对数组进行降序排列
asort() - 根据关联数组的值,对数组进行升序排列
ksort() - 根据关联数组的键,对数组进行升序排列
arsort() - 根据关联数组的值,对数组进行降序排列
krsort() - 根据关联数组的键,对数组进行降序排列
//sort()
c
a
r
s
=
a
r
r
a
y
(
"
V
o
l
v
o
"
,
"
B
M
W
"
,
"
T
o
y
o
t
a
"
)
;
s
o
r
t
(
cars=array("Volvo","BMW","Toyota"); sort(
cars=array("Volvo","BMW","Toyota");sort(cars);
c
l
e
n
g
t
h
=
c
o
u
n
t
(
clength=count(
clength=count(cars);
for(
x
=
0
;
x=0;
x=0;x<
c
l
e
n
g
t
h
;
clength;
clength;x++)
{
echo
c
a
r
s
[
cars[
cars[x];
echo “
”;
}
//rsort()
c
a
r
s
=
a
r
r
a
y
(
"
V
o
l
v
o
"
,
"
B
M
W
"
,
"
T
o
y
o
t
a
"
)
;
r
s
o
r
t
(
cars=array("Volvo","BMW","Toyota"); rsort(
cars=array("Volvo","BMW","Toyota");rsort(cars);
//asort() arsort() 关联数组排序 value
a
g
e
=
a
r
r
a
y
(
"
P
e
t
e
r
"
=
>
"
35
"
,
"
B
e
n
"
=
>
"
37
"
,
"
J
o
e
"
=
>
"
43
"
)
;
a
s
o
r
t
(
age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); asort(
age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");asort(age);
arsort($age);
//ksort() krsort() 关联数组排序 key
a
g
e
=
a
r
r
a
y
(
"
P
e
t
e
r
"
=
>
"
35
"
,
"
B
e
n
"
=
>
"
37
"
,
"
J
o
e
"
=
>
"
43
"
)
;
k
s
o
r
t
(
age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43"); ksort(
age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");ksort(age);
krsort($age);
?>