In this tutorial, you shall learn about functions in PHP, how to define a function, its syntax, with example programs.

Functions

In PHP, functions are blocks of code that can be executed multiple times throughout a script. They can be used to perform specific tasks or calculations, and they can accept arguments and return values.

Syntax of a function

The syntax of a function consists of the keyword function, followed by the function name. Then comma separated parameters enclosed in parenthesis, followed by a block of code enclosed in curly braces.

A simple example for a function is as shown in the following.

function add($a, $b) {
  $temp = $a + $b;
  return $a + $b;
}

where

  1. function is the keyword that tells PHP that you’re defining a function. The keyword is followed by the name of the function.
  2. add is the function name. This is the name you give your function. You should choose a name that reflects what the function does.
  3. ($a, $b) are the function parameters. These are variables that the function expects to receive as input. They are enclosed in parentheses after the function name. If there are multiple parameters, they are separated by commas.
  4. The function body. This is the block of code that the function executes when it is called. It is enclosed in curly braces and can contain any number of statements. In this particular example, we have two statements: the first statement computes the sum of given two numbers, and the second is a return statement.
  5. return $a + $b; is the return statement. This is an optional statement that allows the function to return a value to the calling code. If you want your function to return a value, you include the return statement followed by the value you want to return.
ADVERTISEMENT

Examples

1. Define a function that takes two parameters and return a value

In the following program, we write a function named add(), that expects two numbers as arguments, computes the sum of these two arguments, and returns the sum.

PHP Program

<?php
  function add($a, $b) {
    $temp = $a + $b;
    return $temp;
  }

  $result = add(4, 3);
  echo "The sum is : " . $result;
?>

Output

PHP Function Example

Conclusion

In this PHP Tutorial, we learned how to define functions, and how to write and call them in programs, with examples.