Current Location: Home> Latest Articles> Complete Guide to Creating PHP Functions: Syntax Explained with Code Examples

Complete Guide to Creating PHP Functions: Syntax Explained with Code Examples

M66 2025-08-07

Basic Syntax of PHP Functions

In PHP, a function is a block of reusable code that can be called by its name to perform a specific task. The basic syntax for defining a function is as follows:

function function_name(parameters) {
  // function body
}

When writing a function, follow these steps:

Choose a Function Name

The function name must start with a letter or underscore, followed by any combination of letters, numbers, or underscores to ensure the name is valid and standard.

Specify Parameters (Optional)

Parameters are input values passed to the function, which can be any PHP-supported data types. List zero or more parameters separated by commas inside the parentheses.

Write the Function Body

The function body contains the code that executes the logic of the function.

Practical Example: Calculating the Sum of Two Numbers

The following example defines a simple function that calculates the sum of two numbers passed as arguments:

function addNumbers($num1, $num2) {
  // Calculate the sum of $num1 and $num2
  $sum = $num1 + $num2;
  // Return the result
  return $sum;
}

To use this function, call it with parameters like this:

$result = addNumbers(5, 10); // Result is 15

This allows the function to be reused in different places, avoiding duplicate code and improving maintainability.

Conclusion

Mastering how to create and call PHP functions is essential for writing efficient code. This article introduced the basic syntax of functions, parameter usage, and examples, which are helpful for beginners. Practicing more will help you better understand functions and use them flexibly.