PHP Tutorial 5: Functions

The real power of PHP comes from its functions. It supports both PHP functions as well as user defined functions. Methods reduce the work load of the script. Things that have to be used repeatedly can be written as PHP functions and can be used over again. It brings in the concept of reusability in PHP.

Basically any type of functions can be created using PHP function.

There are some points to be remembered before you start writing a function, here they are:

  1. During function declaration the function name has to be preceded with the function keyword.
  2. Variables used in the functions are within the scope, you can’t use them outside the function block.
  3. You can call the function from anywhere on the page just by using the name of the function.

The syntax for creating a function in PHP is:

function functionName(param)
code to be executed;


php functions

To increase or add up more functionality to a function we use parameters. Parameters like any other programming language takes up input to the function and your function manipulates the inputs and returns you desired output.

Let us show you all what you can do with PHP user defined functions.

A simple logic to display multiplication table using functions.


function maths($var1)
for ($i=1;$i<=10;$i++)
echo "$var1*$i=".$add."<br>";

echo maths(10);

This is what you will be seeing as output.


How does it help?  You don’t have to write code to display multiplication table for each number user wants. Just ask him the number, replace the $var1 with user input and it will be no time before he gets what he wants. Sounds interesting. Yes we will be showing you how to accept inputs from users in our up coming tutorial.


Comments are closed.