PHP Beginnings Ex. #2: Create and Use Variables

For your second PHP exercise, echo the following statement to the browser:

“Twinkle, Twinkle little star.”

Next, create two variables, one for the word “Twinkle” and one for the word “star”. Echo the statement to the browser, this time substituting the variables for the relevant words. Change the value of each variable to whatever you like, and echo the statement a third time. Remember to include code to show your statements on different lines.



Here's the script:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     
  2. "">   
  3. <html xmlns=""  xml:lang="en" lang="en"> 
  4. <head> 
  5. <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" /> 
  6. <title>Twinkle Twinkle</title> 
  7. </head>   
  8. <body>   
  9. <?php 
  11. echo "Twinkle, Twinkle little star. <br/>"; 
  12. //Note that html tags can be included along with the text to be echoed. 
  14. $twinkle="Twinkle"; 
  15. $star="star"; 
  17. //This will print out exactly the same as the first echo statement.
  18. echo "$twinkle, $twinkle little $star.<br/>"; 
  20. $twinkle="Thunder"; 
  21. $star="elephant"; 
  23. /*This one will be different. Exactly what prints will depend 
  24. on what valued you assigned to the variables.*/
  25. echo "$twinkle, $twinkle little $star.";
  27. ?>   
  28. </body> 
  29. </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.