douqian1835 2013-10-10 14:57
浏览 129
已采纳

PHP:for循环和if语句

I am currently studying a beginning PHP programming class and I need some assistance with one assignment I'm trying to solve. The assignment is to create a form where the user can enter a positive integer. Then, use a “for” loop to display that amount of horizontal lines created by the "hr" tag [Hint: <hr size=1 width=50% color='black'>]. Finally, use an if statement to perform “modulus” calculation. When the counter in the “for” loop is an even number set the width of the horizontal line to 50%; otherwise, set the width of the horizontal line to 100%.

Here's the code I have come up with thus far:

<?php

if ($_POST) { // if the form is filled out
$integer = $_POST["pi"];

$i = $integer;

for ($i = 1; $i <= $integer; $i++) {
if ($i % 2) { // modulus operator
echo "<hr size=1 width=50% color='black'>";
} else {
echo "<hr size=1 width=100% color='red'>";
}

}
}
else { // otherwise display the form
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter a <i>Positive Integer</i>:
<input type="text" name="pi" size=5>
<input type="submit" value="Check"></form></p>
<?php
}
?>

I can't post an image yet, but the sample output should be a 50% black horizontal rule, followed by a 100% red horizontal rule, until the integer entered is reached. In between each hr seems to have some spacing.

展开全部

  • 写回答

4条回答 默认 最新

  • doudun5009 2013-10-10 15:09
    关注

    This line:

    $i = $integer;
    

    ...is redundant, as soon as you say for($i = ..., $i will be overwritten. In your case, so it should be. Take that line out to start with.

    Second, I think the problem you're having is that your lines aren't showing as black or red. Reason is that color is a font attribute and you should look at this post to find out how to change your color: Changing the color of an hr element

    I suggest using class='black' and class='red' in your PHP and setting classes up in your CSS.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部