How to create and use custom functions in PHP

Functions in PHP are a great way to organize and modularize your code. In addition to the built-in functions, PHP allows you to create your own custom functions. This provides greater flexibility and reusability in your code.

Syntax

To create a custom function in PHP, use the function keyword followed by the function name, parameter list, and function body block, like this:

function functionName(parameter1, parameter2, ...) {
  // function body
}

Usage Examples

Here are some examples of how to create and use custom functions in PHP:

Example 1: Simple function that returns the sum of two numbers

function sum($num1, $num2) {
  return $num1 + $num2;
}

echo sum(2, 3); // Output: 5

Example 2: Function that calculates the factorial of a number

function factorial($num) {
  if ($num == 0 || $num == 1) {
    return 1;
  } else {
    return $num * factorial($num - 1);
  }
}

echo factorial(5); // Output: 120

Parameter Values

Parameter Description
functionName The name of the function you want to define.
parameter1, parameter2, … The parameters for the function.
// function body The actual code or statements that the function executes.

Technical Details

Property Value
Supported PHP version 4 and later.
Returns Value specified in the function using the return statement, or NULL if no return value is specified.
Scope Functions defined inside a class become methods of that class and have access to all the class members (methods and properties).

For more information on custom functions in PHP, please visit the official PHP documentation.

 

  Written by: Maria Jensen     24-05-2023     Written in: PHP tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *