PHP: for

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.


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.


It isn't clear what the problem is. If the issue is that your HR elements have spaces between them, then removing the default margin will help (at least in Firefox, I'm not sure if all browsers use the same rendering rules on HR).

<hr size="1" width=50% color='black' style="margin:0;" />
<hr size="1" width=100% color='red' style="margin:0;" />

问题在于,您将$ i分配给变量$ integer,因此它们是相同的值。

    <?php
if ($_POST)
{ // if the form is filled out
    $integer = $_POST["pi"];
    for ($i = 1; $i <= $integer; $i++)
    {
        if ($i % 2 ===0)
        { // 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
}
?>
链接地址: http://www.djcxy.com/p/15760.html

上一篇: 如何使横向规则不被拉伸?

下一篇: PHP:for