分支结构和循环结构

一、单一分支结构

<?php
    header("Content-type:text/html;charset=utf-8");
    $a=100;
    $b=200;
    if ($a < $b) {
        echo $a."小于".$b; //如果只有一条语句,黄色的花括号是可以去掉的
    }
?>

二、双向分支结构

<?php
    header("Content-type:text/html;charset=utf-8");
    $a=300;
    $b=200;
    if ($a < $b) {
        echo $a."小于".$b;
    }else{
        echo $a."大于".$b;
    }
?>

三、多向条件分支结构  

<?php
    header("Content-type:text/html;charset=utf-8");
$one=1000;
    switch(1000)
$one=1000;
    switch($one)
$like='美女';
    switch($like)
    $one=1000;
    switch(1000){      //如果您上面给了变量的在判断里面千万不要给值  或者  在里面直接给值
        case 100: echo "100"; break;    //注意:case 后面是  :  号  不是  ; 号
        case 200: echo "200"; break;
        default: echo '没有您想要值';
    }
?>
结果:没有您想的值

四、巢状条件分支结构

<?php
    $sex = 'GRIL';
    $age = '70';
    if ($sex =='MAN') {
        if ($age >= 65) {
            echo '这一个男士已经退休了';
        }else{
            echo '这一个男士还在工作中';
        }
    } else {
        if ($age >=45) {
            echo '这一个女士已经退休了';
        }else{
            echo '这一个女士还在工作中';
        }
    }    
?>
结果:这一女士已经退休了

一、while 循环

 

<html>
<body>
<?php
$i=1;
while($i<=5)
{
    echo "The number is " . $i . "<br>";
    $i++;
}
?>
</body>
</html>
输出:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

二、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循环

<?php
$x=array("one","two","three");
foreach ($x as $value)
{
    echo $value . "<br>";
}
?>

输出:
one
two
three

使用for循环,实现冒泡排序:

<?php
$arr = array(5,3,6,2,8,10);
for($i = count($arr)-1;$i>=0;$i--){
    for($j = 0 ; $j < $i ; $j++){
        if($arr[$j+1] > $arr[$j] ){
            $aa = $arr[$j+1];
            $arr[$j+1] = $arr[$j];
            $arr[$j] = $aa;
        }
    }
}
print_r($arr);
?>

 

posted @ 2017-12-27 20:12  づ開始懂了。。  阅读(214)  评论(0)    收藏  举报