Functions in PHP with examples

A function in PHP is a reusable block of code that performs a specific task. It enables you to group a set of related statements and execute them multiple times throughout your code without having to repeat it.

General form to create a user-defined function in PHP

function functionName(parameter1, parameter2, ...) {
  // function body
  return $returnValue;

"function" is the keyword used to define a function. The "functionName" is an identifier or a name of the function. parameter1, parameter12, and so on are the list of parameters. Now inside the function, we can create some PHP code to define the work of the function. The parameters and the "return" statement are both optional.

General form to call a user-defined function in PHP

functionName(argument1, argument2, ...);

"functionName" is the user-defined function you want to call, and "argument1," "argument2," etc. are the values you want to pass to its parameters. Skip parameters if the function has no parameters.

PHP function example

Consider the following PHP code as a basic example of a function in PHP:

PHP Code
   function codescracker() {
      echo "Hello there";
Hello there

This PHP code defines a function named codescracker() that does not take any input parameters, but when called, it outputs the string "Hello there" to the browser or console using the echo statement. After defining the function, the code then immediately calls the function by invoking its name, codescracker(), followed by parentheses. The function call is written outside of the function definition, so it can be used elsewhere in the PHP script.

Here is another example that accepts two parameters and also returns a value.

PHP Code
   function add($x, $y) {
      $sum = $x + $y;
      return $sum;
   $a = 10;
   $b = 20;
   $res = add($a, $b);
   echo $res;

This is a short piece of PHP code that calls the function "add" to add up two variables and displays the results. The code accomplishes the following:

Advantages of functions in PHP

Disadvantages of functions in PHP

PHP Online Test

« Previous Tutorial Next Tutorial »

Liked this post? Share it!