PHP Functions

PHP Functions

PHP Functions

A function in PHP is a block of reusable code that performs a specific task. Functions help in organizing code, improving reusability, and reducing redundancy. PHP has both built-in functions (like strlen(), array_push(), etc.) and user-defined functions.

1. Defining and Calling a Function

Syntax:

function functionName() { // Code to execute }

Example:

function greet() { echo "Hello, World!\n"; } greet(); // Calling the function

Output:

Hello, World!

2. Function with Parameters

You can pass parameters (also called arguments) to functions.

Example:

function greetUser($name) { echo "Hello, $name!\n"; } greetUser("John"); greetUser("Jane");

Output:

Hello, John! Hello, Jane!

3. Function with Return Value

Functions can return values using the return statement.

Example:

function add($a, $b) { return $a + $b; } $result = add(5, 3); echo "The sum is: $result\n";

Output:

The sum is: 8

4. Default Parameter Values

You can set a default value for parameters.

Example:

function greet($name = "Guest") { echo "Hello, $name!\n"; } greet(); // Uses default value greet("Alice"); // Uses given parameter

Output:

Hello, Guest! Hello, Alice!

5. Function with Multiple Parameters

A function can accept multiple parameters.

Example:

function multiply($a, $b, $c) { return $a * $b * $c; } echo multiply(2, 3, 4);

Output:

24

6. Passing Arguments by Reference

By default, function parameters are passed by value. If you want to modify the original variable, use pass by reference with the & symbol.

Example:

function increaseValue(&$num) { $num += 10; } $value = 5; increaseValue($value); echo $value; // Modified value

Output:

15

7. Variable-Length Arguments (... Operator)

PHP allows functions to accept a variable number of arguments using the ... operator (also called variadic functions).

Example:

function sumAll(...$numbers) { return array_sum($numbers); } echo sumAll(1, 2, 3, 4, 5); // Sum of all numbers

Output:

15

8. Anonymous Functions (Lambda/Closure)

PHP allows defining functions without names, known as anonymous functions or closures.

Example:

$greet = function($name) { return "Hello, $name!"; }; echo $greet("John");

Output:

Hello, John!

9. Arrow Functions (PHP 7.4+)

Arrow functions are a shorter way to define anonymous functions.

Example:

$multiply = fn($a, $b) => $a * $b; echo $multiply(4, 5);

Output:

20

10. Recursive Functions

A recursive function is a function that calls itself.

Example: Factorial Calculation

function factorial($n) { if ($n <= 1) { return 1; } return $n * factorial($n - 1); } echo factorial(5);

Output:

120
  • 5! = 5 × 4 × 3 × 2 × 1 = 120

11. Built-in PHP Functions

PHP provides many built-in functions for different tasks.

String Functions

  • strlen($str) → Returns the length of a string.
  • strtoupper($str) → Converts string to uppercase.
  • strtolower($str) → Converts string to lowercase.
  • strpos($str, "word") → Finds the position of a word in a string.
  • str_replace("old", "new", $str) → Replaces text in a string.

Example:

$text = "Hello World"; echo strlen($text); // 11

Array Functions

  • count($array) → Returns the number of elements in an array.
  • array_push($array, $value) → Adds an element to the end of an array.
  • array_pop($array) → Removes the last element of an array.
  • sort($array) → Sorts an indexed array in ascending order.

Example:

$fruits = ["Apple", "Banana", "Cherry"]; array_push($fruits, "Mango"); print_r($fruits);

Output:

Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Mango )

12. Function Overriding (Not Supported in PHP)

Unlike some programming languages, PHP does not support function overloading (i.e., defining multiple functions with the same name but different parameters). However, you can achieve similar behavior using default parameters or variadic functions.

Example (Simulating Function Overloading with ... Operator)

function display(...$values) { foreach ($values as $value) { echo $value . "\n"; } } display("Hello"); display("Hello", "World");

Output:

Hello Hello World

13. Global vs Local Variables in Functions

Local Variable

A variable declared inside a function is local and cannot be accessed outside.

Example:

function myFunction() { $x = 10; // Local variable echo $x; } myFunction(); // echo $x; // This will cause an error

Global Variable

A global variable is declared outside a function and can be accessed using the global keyword.

Example:

$x = 10; function myFunction() { global $x; echo $x; } myFunction();

Output:

10

Conclusion

  • PHP functions organize code and improve reusability.
  • Functions can accept parameters and return values.
  • You can define anonymous functions and arrow functions for shorter code.
  • PHP provides built-in functions for strings, arrays, and math operations.
  • Recursion allows functions to call themselves for complex calculations.
Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close