PHP Functions


Today we will learn about functions in this PHP Functions tutorial.

  • What are Functions?
    • Functions are the language constructs used to make the programming very easy.
    • If same code is needed in most of the places in the same program, it is written that many times.
    • But writing the same code so many times increases the program length as well as confusion in understanding.
    • To avoid this problem, functions are used.
    • Function is a block of statements that can be called and used wherever required.
    • The code is written once in the function and wherever the code is required, the function is called by its name instead of writing the whole code again.
    • Functions are of 2 types:
      1. Inbuilt functions
      2. User defined functions
      1. Inbuilt functions:
        • Inbuilt functions are the functions which are already written in the system.
        • These functions are to be used directly using the syntax they follow.
        • Examples of such functions are echo, print, var_dump(), settype(), gettype etc. that we have seen before.
      2. User-defined functions:
        • User-defined functions are those that are not available in the system.
        • Its name itself indicate that these functions are user defined i.e. they are written by the user according to his/her requirement.
        • User can define the function following the rules used to writing and calling it.
    • Function has 2 steps:
      1. function definition
      2. Function call.
    • A function doesn’t execute unless and until it is called.
    • Actually the built-in functions are written already, we simply call them in our program.
    • Syntax of a function definition is given below:
    • In the syntax of function definition given above, function is a keyword used to declare a function.
    • Besides it we need to write a function_name. Name of the function can start with a letter or an underscore (_), but not with a number.
    • The function name always has parenthesis after it. Actually the parentheses indicate, it is a function.
    • The opening and closing curly braces forms the function block which contains number of statements to be executed.
    • The function executes only when it is given a call.
    • Syntax for function call is given below:
    • Function can be called with the function_name followed by parenthesis and the statement is terminated by a semi-colon.
    • Let us see an example of function.
    • Let us find out the numbers divisible by 3 in a given range of numbers.
    • Create a new folder named functions in the htdocs folder in xampp folder situated in C drive. Now open a new notepad++ document and save it as index.php in the newly created functions folder.
    • Write the following code in index.php file:
    • In the above code we have used PHP code with HTML.
    • We know that with HTML, PHP can be written in head section or body section.
    • In this code we have written the function definition in the head section by inscribing it in the PHP tag and called it for execution in the body section.
    • Let us understand the function:
    • The function code is shown below:
    • In the function given above the keyword function is used to declare it. Function name is divisible_by_3 and it has parenthesis besides it.
    • The function name should always be such that it reveals its purpose.
    • The code to be executed is written inside the function block.
    • The variables $n1 and $n2 are declared with value 1 and 20 respectively. The variables inside a function are local to the function.
    • Now we want to find out the numbers divisible by 3 in a range of 1 to 20. For this we will have to divide each number and check whether it is divisible by 3 or not. So we need a loop to repeat the same process of division for each number.
    • In the above function we used a while loop, we want to repeat the process on 20 numbers, hence the condition in while statement is given as $n1<=$n2. So the while loop will repeat till the value of $n1 is less than or equal to the value of $n2 variable.
    • Once the control enters the while block after satisfaction of the condition, it checks whether the number is divisible by 3 using the if statement.
    • Here, in the if statement first the value in variable $n1 is divided by 3 using modulus (%) which gives remainder after division. This remainder is then compared with zero. If they both are equal then the number is divisible by 3, since a number completely divisible by a number gives remainder zero after division.
    • If the number is divisible in the above code, it is displayed on the webpage using statement and if it is not divisible completely, it is not displayed.
    • We haven’t given opening and closing curly braces to the if block because we have only one statement to execute in it.
    • Next the value of $n1 is incremented by 1 and again the loop is repeated.
    • In this way, all the 20 numbers are checked for their divisibility by 3.
    • When the value of $n1 becomes 21, the loop terminates because the condition fails.
    • If we write this function definition only, it will not at all execute.
    • To allow the function to execute, it should be given a call.So to call a function the statement is used where divisible_by_3 is a function name which is followed by parenthesis.
    • When a function is called, the control jumps to its definition and executes it. Then after complete execution of the function it again returns to the statement from where it was called.
    • The output is shown below:

    • fig 1

  • Functions with Arguments:
    • The function we saw in the above code was a simple function without arguments. Now we will learn to pass arguments to the function.
    • Arguments are nothing but simple variables that are used to pass values to the function.
    • Arguments are also called as parameters.
    • The arguments are passed in the parenthesis of function that follows the function name during the function call. Values of these passed arguments are then used in the function definition for some processing.
    • More than one argument can be passed separated with a comma (,).
    • Let us see an example.
    • Let us add two numbers in a function add which are passed as arguments in the function call.
    • Write the following code in index.php file:
    • Here we will first start with the function call.
    • We can see that we have called a function named Add() and passed 2 arguments 20 and 30 separated by comma in it.
    • This function call will call the function Add().
    • Let us see the function definition.
    • In this function definition the function Add() also has two variables in its parenthesis. These variables are used to receive the argument values passed in the function call. So function definition should also have the same number of parameters in its parenthesis as the passed arguments in the function call.
    • In the above code, the values 20 and 30 passed in the function call to Add() are received by variables $a and $b respectively.
    • Addition of these values is performed in the function and it is displayed on the webpage.
    • So remember, the arguments passed in the function call are received in the parameters of the function definition and then used further.
    • The output is shown below:

    • fig 2

  • Functions with default argument values:
    • Functions in PHP have the facility to assign default values to the parameters passed to them.
    • Imagine that we have a function with one argument.
    • We made a call to the function and forgot to provide value for the argument. This will give error asking you to pass the argument value.
    • This will not happen if you already provide a default value to the parameter in the function definition. Even if you forget to pass value to the argument during the function call, it will use the default parameter.
    • Let us try an example of this type.
    • We will take an example of greeting each other.
    • Write the following code in index.php file:
    • Here, we have a function definition for a function Greeting() with one parameter $greet.
    • We have assigned a value “Good Morning” to this parameter in the parenthesis itself using the assignment operator.
    • Then the echo statement is executed which will greet everybody.
    • Now let us study the function calls.
    • We have called the Greeting function thrice with different argument values.
    • The function call has the argument value “Good AfterNoon”. This will call the function, override the default value of the parameter and print the statement Good AfterNoon everybody!
    • The next function call has no parameter, in this situation the default parameter value is used and the statement Good Morning everybody! is displayed.
    • In the third call the statement Good Evening everybody! is displayed overriding the default value of the parameter.
    • In this way if default parameter value is given, it is overridden if the argument value is passed in the function call and used when it is not passed in the function call.
    • The output is shown below:

    • fig 3

  • Function returning a value:
    • Till now we saw functions taking arguments and printing the output using echo statement in function itself.
    • The variables declared inside the function are local and cannot be accessed outside the function.
    • In such situation if we want the value calculated inside the function to be accessed outside it, there should be some mechanism.
    • We can achieve it by using the return statement.
    • The word return is a keyword used to carry a value outside the function.
    • A return statement can return only one value at a time.
    • Syntax of return statement is given below:
    • The return statement can contain a variable containing value or simply a value or an expression.
    • An expression passed to the return statement is evaluated and its result is returned by the function.
    • The parenthesis in return statement is optional. But it is better if it is used during expressions are given to return statement.
    • Let us have an example:
    • We will modify the Add() function used before to return the addition value.
    • Write the following code in index.php file:
    • Let us first see the function definition of function Add().
    • It has 2 arguments passed to it and the values in the arguments are added and stored in variable $c.
    • This variable is returned by the function Add() through the return statement as stated below:
    • We can even eliminate the statement from the function and write the return statement as follows:
    • Here the expression $a+$b evaluate to 200 (100+100=200) and returns 200 to the function call.
    • This return statement will return the value to the function call statement.
    • The function call statement is given below:
    • We had discussed earlier that whenever a function is called, the control jumps to the function definition and after complete execution of the function it again returns to the function call.
    • Thus the return statement returns the value to this function call itself.
    • Now this value needs to be stored in any variable or it can be displayed directly.
    • In our example we have stored the value 200 in the variable $ans and the displayed it using the statement
    • If we don’t want to display it, we can use it in some other calculation etc.
    • The output is shown below:

    • fig 4

Thus we studied how a function is useful and how to use it in this PHP Functions tutorial.


Please enter your comment!
Please enter your name here