选择与循环结构
php的选择结构与循环结构和C语言的一摸一样,过多的就不提了,我们就简单描述下,然后直接看例题
选择结构
if-else语句
结构
if(条件)
{
...
}else
{
...
}
switch语句
结构
switch(条件)
{
case 情况1:
break;
case 情况2:
break;
case 情况3:
break;
default: ...
}
例题1:表单里有固定的选项,用户手动选择一个,我们根据用户选择的自动输出一句话。
/*2.在表单选择对应的项目,根据不同选择进行输出*/
echo <<<"post"
<form action="" method="post">
<label>please input num</label>
<input type="text" name="choice" list="cars">
<input type="submit" value="pass">
<datalist id = "cars">
<option>html</option>
<option>javascript</option>
<option>css</option>
</datalist>
</form>
post;
if(isset($_POST["choice"]))
{
switch($_POST["choice"])
{
case "html":
echo "<script>alert(\"html is a good language\")</script>";
break;
case "javascript":
echo "<script>alert(\"javascript is a good language\")</script>";
break;
case "css":
echo "<script>alert(\"css is a good language\")</script>";
break;
default:
echo "fuck you!";
break;
}
}
下图是整个过程


例题2:在表单里输入一个数字,根据数字在页面弹出提示框,是偶数跳出偶数的提示框,否则跳出奇数的提示框
echo <<<"post"
<form action="" method="post">
<label>please input num</label>
<input type="text" name="num">
<input type="submit" value="pass">
</form>
post;
//检测是否表单有数据
if(isset($_POST["num"]))
{
if($_POST["num"] %2 ==0)
{
echo '<script>alert("is ou shu");</script>';
}else
{
echo '<script>alert("is ji shu");</script>';
}
}
此时的浏览器页面如下图所示,我分别输入了奇数和偶数




循环结构
while
while(条件)
{
...
}
do-while
do
{
...
}while(条件);
for
for(初始值;条件;运算)
{
...
}
例题:在表单里输入行和列,根据输入的行和列自动生成对应的表格。
<?php
/*1.用户在表单输入行和列的数字,*/
echo <<<"post"
<form action="" method="post">
<label>row</label>
<input type="text" name="row">
<label>clo</label>
<input type="password" name="clo">
<input type="submit" value="pass">
</form>
post;
//2.根据数据生成对应的表
if(isset($_POST["row"]) && isset($_POST["clo"]))
{
echo '<table border="1" cellpadding="7" cellspacing="0">';
for($i=0;$i<$_POST['row'];$i++)
{
echo '<tr>';
//输入列
for($j=0;$j<$_POST['clo'];$j++)
{
echo '<td>'.($i*$_POST['clo']+$j).'</td>';
}
echo '</tr>';
}
echo '</table>';
}
下图是整个过程的演示


网友评论