PHP Functions
User-Defined Functions
A user-defined function in PHP is a function that you can create to perform specific tasks. This allows you to reuse code and organize your program in a modular way.
Syntax for Defining a Function:
function functionName($parameter1, $parameter2, ...) { // Code to be executed return $result; // Optional return statement }
- function: The keyword used to define a function.
- functionName: The name of the function (should be meaningful and follow naming conventions).
- $parameter1, $parameter2: Optional parameters passed to the function.
- {}: The block of code that defines what the function will do.
Example 1: Basic Function without Parameters
<?php // Define a simple function to print a greeting function greet() { echo "Hello, welcome to PHP!<br>"; } // Call the function greet(); // Output: Hello, welcome to PHP! ?>
Example 2: Function with Parameters
<?php // Define a function that takes parameters function addNumbers($a, $b) { $sum = $a + $b; return $sum; // Return the sum } // Call the function with arguments $result = addNumbers(5, 10); echo "The sum is: " . $result; // Output: The sum is: 15 ?>
Example 3: Function with Default Parameters
<?php // Function with default parameters function greetUser($name = "Guest") { echo "Hello, " . $name . "!<br>"; } // Call the function with no arguments (uses default) greetUser(); // Output: Hello, Guest! // Call the function with an argument greetUser("Alice"); // Output: Hello, Alice! ?>
Basic Variable Function
<?php // Define two functions function greet() { echo "Hello, welcome to PHP!<br>"; } function farewell() { echo "Goodbye, have a nice day!<br>"; } // Variable function to call greet $functionToCall = 'greet'; $functionToCall(); // Output: Hello, welcome to PHP! // Variable function to call farewell $functionToCall = 'farewell'; $functionToCall(); // Output: Goodbye, have a nice day! ?>
Variable Length Argument Functions
func_num_args: This function returns the number of arguments passed to the current function.
<?php function printArguments() { $arg1 = func_get_arg(0); // 0 is the index for the first argument echo "First argument: $arg1<br>"; $arg2 = func_get_arg(1); // 1 is the index for the second argument echo "Second argument: $arg2<br>"; } printArguments("Apple", "Banana"); // Output: // First argument: Apple // Second argument: Banana ?>
func_get_args: Retrieves all arguments passed to the function and returns them as an array.
<?php function printAllArguments() { $args = func_get_args(); foreach ($args as $arg) { echo "Argument: $arg<br>"; } } printAllArguments("Apple", "Banana", "Cherry"); // Output: // Argument: Apple // Argument: Banana // Argument: Cherry ?>
Tags:
php