PHP Control Structures Ex. #3: Simple For Loop
Loops are very useful in creating lists and tables. In this PHP exercise, you will use a loop to create a list of equations for squares.
Using a for loop, write a script that will send to the browser a list of squares for the numbers 1-12.
Use the format, "1 * 1 = 1", and be sure to include code to print each formula on a different line.
 
 
Here's the script:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
<title>Squares for the Numbers 1-12</title>
</head>
<body>
<h2>Squares for the Numbers 1-12</h2>
<?php
for ($x=1; $x<=12; $x++){
$result = $x * $x;
echo "$x * $x = $result <br />\n";
}
?>
</body>
</html>
See the output of the script in a separate window here. You can also view the output's HTML source from the new window, if you need to check that.
To open a PHP code editor in a new tab, click here.
Comments
not be be rash
Not to be rude, but I think that this lesson could use a little re-wording. I was a little confused, as I was assuming you wanted actual squares like table squares. making a list would probably be a little easier to understand. Good work with the site, I really enjoy it.
Glad you enjoy it
Glad you enjoy the site. Regarding this exercise, we feel that giving the example equation "1*1=1" makes it clear what kind of squares are being requested.
where is the new line
hi... Probably no one is reading this again cos most comments were last years. I tried d exercise but in ur answer- i didnt find d script for d new lines. Here is mine- i got d ans but worried if my < ol> is unneccessary:
for($a=1;$a <= 12; $a++){
$b= $a*$a;
echo "< ol>$a*$a = $b < /ol>;
}
good work here.. Can more exercises be created? Thx!
alternative script
$foo = 1;
while($foo <= 12) {
echo "$foo * $foo = ". pow($foo, 2)."";
$foo++;
}
nice!
a hardened javascript developer, I really want to learn how to bring more backend experience to my users, not to mention learning how everything works behind the scenes, and being able to get my hands dirty in various CMSs when things go awry. this site is great for getting sanding off the awkward edges between the languages, while still hammering home the basics. excellent! : )
Different solution using string concatenation and HTML5
<?php
{
}
?>
pow solution
Why used BR tag with \n
echo "$x * $x = $result \n"
Why you have used BR tag and \n.
Both are for new line. Why do you used both? However, BR tag is enough.. Am I right?
Answered in earlier exercise.
See http://phpexercises.com/php-variable-data-types-exercise.html
I thought we were supposed to print the quotes too...
This is how I printed the quotes.
Here's mine using pow
Used the pow() function to get the results.
<?php
}
?>