Follow:  Follow PHPExercises on Twitter  Follow us on Facebook

PHP Control Structures Ex. #2: Simple Loops

In this PHP exercise, you will put all the loops through their paces. Write a script that will print the following to the browser:

abc abc abc abc abc abc abc abc abc

xyz xyz xyz xyz xyz xyz xyz xyz xyz

1 2 3 4 5 6 7 8 9

  1. Item A
  2. Item B
  3. Item C
  4. Item D
  5. Item E
  6. Item F

Create the 'abc' row with a while loop, the 'xyz' row with a do-while loop, and the last two sections with for loops. Remember to include HTML and source code line breaks in your output. No arrays allowed in this solution.

 

Comments

$count = 0;
while (++$count <= 9) echo "abc ";
echo "<br />"; 
$count = 0;
do
{
    echo "xyz ";
} while (++$count <9);
echo "<br />"; 
for ($cont = 1; $cont <= 9; ++$cont) echo "$cont ";
echo "<br />"; 
$alfabeto = "ABCDEFG";
for ($conta = 1; $conta <= 6; ++$conta)
{
    echo "$conta. ITEM " . substr($alfabeto,$conta-1,1) . "<br />";
}

This is great! Glad to see someone contribute alternate PHP to solve the puzzle.

Good job! I like the way you used the substr() function to produce the sequence of letters.

Another good solution for the last part can be using the following. Is almost the same solution but i think is clever to.

<?php

$a = array(0, A, B, C, D, E, F, G);
 
 for ($x=0; $x<8; $x++){
     echo "<li>Item ".$a[$x]." </li>\n";} 
   echo "</ol>\n"
?>

or

<?php

$a = array(0, A, B, C, D, E, F, G);
 
 for ($x=0; $x<7; $x++){
  echo "<li>Item ".$a[$x-1]." </li>\n";} 
 echo "</ol>\n"
?>

I like your answer the most but I would prefer to go like this at the end:

<?php

$arr = array ("A", "B", "C", "D", "E", "F", "G");

echo "\n<ol>";

for ($x = 0; $x < count($arr); $x++) {
echo "<li>item ".$arr[$x]."</li>\n";	
}
echo "\n</ol>";
?>

Thank you for your contribution as well, sidman77. I'm curious why both you and xpoststudio4 went to the letter G in your arrays, since the exercise stops at F. I like the fact that you used count() in your for loop; all you have to do is change the array, and you're good to go.

You also make it clear that an array is a natural way to solve this problem. Even more motivation for me to edit the wording of the exercise. Thanks!

Thanks for posting another version, xpoststudio4. There are a couple of problems with your code. The code you posted here omits the opening <ol> tag, and I'm not sure why the first element in both arrays is 0, since that wasn't requested in the exercise. With no quotes around the array elements, this code generates undefined constant errors.

I want to thank you, though, for making me aware that the exercise can be solved with an array. This exercise comes before the section on arrays, and the intention was to do it without. Looks like you caught a bug for me. Thanks! I've just changed the instructions.

Referring only to the last part of the exercise, I have found out that we can also access single characters in a string by using square brackets.

  1. $string = "ABCDEFG";
  2. for ($j=1;$j<7;$j++) {
  3. 	echo "$j. Item ".$string[$j-1],"<br/>\n";
  4. }

And to the people that made all this (website with PHP exercises) possible, I thank you. Keep up the good work!

sir i can't understand why $conta-1,1 . . can you please explain that sir ?. .thank you . .

I am still learning and was unaware that you could increment characters. So...

echo "<ol>";
for ($item = 65; $item <=70; $item ++){
echo "<li>Item " . chr($item) . "</li>";
}
echo "</ol>";

I used characters from the ascii table instead. Could be useful to know anyhow.

Thank you for providing yet another excellent solution to the puzzle.

BTW, we edited your post to use HTML entities for the < and > symbols, so the tildes were not necessary.

$alpha="A";
for ($j = 1; $j < 7; $j++) {
echo $j . ".Item " . $alpha . "";
$alpha++;
}

This may be over-simplifying, but steering clear of an html ordered list (as less generic and flexible), the last part can be just:

  1.   $x=1;
  2.   $y=A;
  3.  while ($x<=6)
  4.   {
  5.  print $x . ". " . "Item " . $y . "<br>";
  6.   $x++;
  7.   $y++;
  8. }

Yes, this works. Revise your code to use a for loop and this fits the exercise very well.

  1. for($a=0;$a<9;$a++)
  2.      {
  3. 	   echo "abc ";
  4.  
  5. 	 }
  6. 	  echo "<br/>";
  7.  
  8. 	  echo "<p>";
  9.  
  10.    for($b=0;$b<9;$b++)
  11.      {
  12. 	   echo "xyz ";
  13. 	 }
  14.        echo "</p>";
  15.  
  16. 	  echo "<br/>";
  17.        echo "<p>";
  18.    for($c=1;$c<=9;$c++)   
  19.      {
  20. 	   echo "$c ";
  21. 	 }
  22. 	  echo "</p>";
  23.     echo "<br/>";
  24.  
  25. 	  echo "<p>";
  26. 	   echo "<ol>";
  27.    for($d='A';$d<'G';$d++)
  28.      {
  29. 	  echo "<li>Item $d </li>";
  30. 	 }
  31. 	   echo "</ol>";
  32. 	  echo "</p>";

  1. <?php 
  2. $x=0;
  3. echo ('<br>');
  4. echo ('<br>');
  5. while ($x++ < 9) {
  6.     echo ('abc ');
  7.     }
  8. $x=0;
  9. echo ('<br>');
  10. echo ('<br>');
  11. do {
  12.     echo ('xyz ');}
  13.     while ($x++<8);
  14.  
  15. $x=0;
  16. echo ('<br>');
  17. echo ('<br>');
  18. for ($x=1; $x < 10; $x++) echo("$x ");  
  19.  
  20. $x=0;
  21. echo ('<br>');
  22. echo ('<br>');
  23. define("LetterA", "65") ;
  24. $CurrentItemAlpha = chr(LetterA);
  25. for ($x=1; $x < 7; $x++, $CurrentItemAlpha = chr(LetterA-1+$x)){
  26.      echo("$x. Item $CurrentItemAlpha<br>"); 
  27.      }    
  28.  
  29. ?>

for this exercise i used switch case :D
im so stupid :)

  1. <html>
  2.   <body>
  3.     <?php
  4. 	//while
  5. 	$a = 'abc';
  6. 	$i = 1;
  7. 		while($i < 10){
  8. 			echo $a.'&nbsp';
  9. 			$i++;
  10. 		}
  11. 		echo '<br />';
  12. 	//do-while
  13. 	$z = 1;	
  14. 	$b = 'xyz';
  15. 		do{
  16. 			echo $b.'&nbsp';
  17. 			$z++;
  18. 		}while($z<10);	
  19. 		echo '<br />';
  20. 	//loop for 1 2 3 4 5 6 7 8 9
  21. 	for($i = 1; $i < 10; $i++){
  22. 		echo $i.'&nbsp';
  23. 	}
  24. 	echo '<br />';
  25. 	//loop for 1. Item A
  26. 	for($i = 1; $i < 7; $i++){
  27. 		switch($i){
  28. 			case 1:
  29. 				echo $i.'. Item A <br />';
  30. 				break;
  31. 			case 2:
  32. 				echo $i.'. Item B <br />';
  33. 				break;
  34. 			case 3:
  35. 				echo $i.'. Item C <br />';
  36. 				break;
  37. 			case 4:
  38. 				echo $i.'. Item D <br />';
  39. 				break;
  40. 			case 5: 
  41. 				echo $i.'. Item E <br />';
  42. 				break;
  43. 			case 6:
  44. 				echo $i.'. Item F <br />';
  45. 				break;
  46. 			case 7:
  47. 				echo $i.'. Item G <br />';
  48. 		}
  49. 	}
  50. ?>
  51. </body>
  52. </html>

You got the answer right...? I did switch too :P

Here what i've created :) :

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    
  2.  "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"></a>   
  3.  <html xmlns="<a href="http://www.w3.org/1999/xhtml"">http://www.w3.org/1999/xhtml"</a>  xml:lang="en" lang="en">
  4. <head>
  5. <body>
  6.     <?php
  7.     $variabila=1;
  8.  
  9.     while ($variabila <10)
  10.     {
  11.         echo "abc ";
  12.         ++$variabila;
  13.     }
  14.     echo ".<br/>";
  15.  
  16.  $variabila=1;
  17.     do echo "xyz ";
  18.         while (++$variabila <10);
  19.  
  20.     echo ".<br/>";
  21.  
  22.  
  23.     for ($variabila=1; $variabila <10; ++$variabila)
  24.     echo $variabila;
  25.  
  26.     echo ".<br/>";
  27.  
  28.     $litere= "A";
  29.     $x=1;
  30.     for ($variabila=1;$variabila <7; ++$variabila, ++$litere, ++$x)
  31.     {
  32.     echo "$x " . " .Item " . $litere . "<br/>";
  33.     }
  34. ?>
  35. </body> 
  36. </head>

P.S. I receive a lot of Server errors related to your database saying "too much connections". Probably you should take a look on that.

Regards!

Thanks for using the SyntaxHighlighter tags for your code!

Regarding the server errors, yeah, we know. The site doesn't really pay for itself, so we use free hosting, and it has frequent errors. Keep trying, and it's usually back up pretty quick. Be glad that the site will stay up (with errors), even if we run short of funds.

Hi everybody.

I found interesting creating the sequence of letters instead of writing it every time. So here is my code. Hope it´s useful.
Regards.

 <?php
	$letter = "a";
	$letterX = "x";

	echo "<p>\n"; 
	$i = 1;
	
   while ($i < 10){
                                // this block of "whiles" creates a sequence of letters;
		while ( $letter !== "d")
		{
			$sequenceLetters = $letter; 
			echo $sequenceLetters;
			$letter++;
		}
	 echo " ";  // creates space between sequence of letters.
	 $letter = "a" ;  // we need to reset the variable to its original value 
                          //to start looping again.
	 $i++;}
	 echo "</p>\n";
	 echo "<p>\n";
	 
	
	$counter = 1; 
	do{
	 // this block of "do" creates a sequence of letters;
		$i = 1;
		do{
			$sequenceLetters = $letterX; 
			echo $sequenceLetters;
			$letterX++;
			$i++;
		  } while ( $i < 4 ); // I found the best way using numbers here 
                                      //because increment was not stopping at "z";
		$counter++;
		$letterX = "x";
		echo " ";
	} while ( $counter < 10);

	 echo "</p>\n";
	 echo "<p>\n";
		for ($i = 1; $i < 10; $i++)
		{	
			echo "$i "; 
		}
	 echo "</p>\n";
	 echo "<ol>\n";
		for ($item = "A"; $item <= "F"; $item++)
		{
			echo "<li>Item $item</li>\n"; 
		}
	 
	 echo "</ol>\n";
 ?>

I didn't know that you could use letters in the for loop argument!! :D

<?php 

$abc = 1;
while ($abc < 10){
	echo 'abc ';
	$abc ++;
}
//end of ABC while loop
echo '<br /><br />';

$xyz=1;
do {
	echo 'xyz&nbsp';
	$xyz ++;
}
while ($xyz < 10);
// end of XYZ do while loop
echo '<br /><br />';

for ($i=1; $i<10; $i++ ) {
	echo $i.'&nbsp';
}
//end of 1-9 for loop
echo '<br /><br />';

for ($i=1; $i<7; $i++){
	switch ($i) {
		case 1:
			$letter = 'A';
			break;
		case 2:
			$letter = 'B';
			break;
		case 3:
			$letter = 'C';
			break;
		case 4:
			$letter = 'D';
			break;
		case 5:
			$letter = 'E';
			break;
		case 6:
			$letter = 'F';
			break;
	}
	echo $i.'.'.' Item '.$letter.'<br />';
}
//end of for loop 1. Item A ~ 6. Item F
?>

For the last part, I thought those are hexadecimal numbers. Since A,B,..,F in hex is equal to the numbers 10,11,..,15 in decimal. My solution is a one line short and simple code:

for ($counter=10;$counter <= 15;$counter++) 
echo "<li>Item ".strtoupper(dechex($counter))."</li>";

(oops, it won't fit into a single in this small display box but it really is just one short line in notepad :D)
dechex converts the variable to hexadecimal and strtoupper makes it uppercase.

Does it matter that traling spaces are generated by the output? I'm sure people will hate me but the output is different than the exercise statement led me to believe. To avoud the trailing spaces in the first 3 lists I did this:

//while loop
	$counter=0;	
	echo "<p>abc";
	while($counter<8) {
		echo " abc";
		$counter++;
	}
	echo "</p>\n";
//do loop
    $counter=0;
	echo 'xyz';
	do {
		echo ' xyz';
		$counter++;
	} while($counter<8);
	echo "</p>\n";
	
//1st for loop
	echo "<p>";
	for($counter=1; $counter<9; $counter++) {
		echo "$counter ";
	}
	echo "$counter</p>\n";

Is there a better way and would the spaces make any differences in a real-life application?