douqian1835 2013-10-10 22: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 23: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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀