By using this site you agree to the use of cookies and related technologies.

Learn more

PHP Functions

Functions are used to create a block of code, that we want to run multiple times. Creating a Function allows us to call this Function, anywhere in the script. This Tutorial is about Functions in PHP.

Edited: 2016-09-24 03:51

Functions in PHP consists of code chunks, which are usually repeated elsewhere in your scripts. One advantage of using functions, is that you can reduce the size of your scripts, and make them much easier to maintain by reducing dublicated code.

For instance, if you have a chunk of code that connects to the database, then it is easier to keep this in one place, inside a function. Doing this allows you to easily update it, since you now only need to change one function, rather then change the code in all the locations where it is being used.

When functions are discussed in object oriented PHP, they will often be referred to as Methods.

Your first Function

This Function is called ContentAd, because we use it to output the header in our pages.

<?php
function ContentAd(){
// validation

echo '<div class="Advertisement"><a href="http://beamtic.com/">Beamtic Tutorials</a></div>';

}
?>

Whenever we call the above function in our scripts, the code inside of it will be executed. A call to the above function would give us the following output:

<div class="Advertisement"><a href="http://Beamtic.com/">Beamtic Tutorials</a></div>

Calling the function

To call Functions in PHP, you would simply write the name of the Function, in this case ContentAd(); whenever needed. Example follows:

<?php
  // First define the Function
function ContentAd(){
// validation

echo '<div class="Advertisement"><a href="http://Beamtic.com/">Beamtic Tutorials</a></div>';

}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">

  <head>
  <title>My first Website</title>

  </head>

  <body>
<?php
  // Then call the Function somewhere else in the Script.

  ContentAd();

?>
  </body>

</html>

The next Tutorial is about Function Arguments