Follow:  Follow PHPExercises on Twitter  Follow us on Facebook

PHP Functions Ex. #1: Simple Function

Functions in PHP can help automate repetitive tasks and enable you to reuse code with a simple function call. For your first function, we'll keep it really simple.

For this PHP exercise, create a function called "hello" that outputs that phrase we all know and love, "Hello, World!" to the browser. Call the function.

 

Here's the code:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2.      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3.  
  4. <html xmlns="http://www.w3.org/1999/xhtml"  xml:lang="en" lang="en">
  5. <head>
  6. <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
  7. <title>Hello Function</title>
  8. </head>
  9.  
  10. <body>
  11. <h2>Hello Function</h2>
  12.  
  13. <?php
  14. //Define function.
  15. function hello(){
  16.   echo "Hello, World!";
  17. }
  18.  
  19. //Call function.
  20. hello();
  21. ?>
  22.  
  23. </body>
  24. </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.