In PHP, functions are reusable blocks of code that perform a specific task. Functions can take parameters (input) and return a value (output), making them very versatile and powerful. Here’s an example of a simple PHP function:

// Define a function that takes two parameters and returns their sum
function add($a, $b) {
return $a + $b;
}

// Call the function with two arguments
$result = add(3, 4);

// Output the result
echo $result; // Output: 7

In this example, we define a function called “add” that takes two parameters ($a and $b) and returns their sum. We then call the function with two arguments (3 and 4) and assign the result to a variable called $result. Finally, we output the result using the echo statement.

Here are some other things to keep in mind when working with functions in PHP:

  • Function names must start with a letter or underscore, followed by any combination of letters, numbers, and underscores.
  • Functions can have optional parameters, which are specified with a default value. For example, we could modify our “add” function to have a default value of 0 for $b, like this:function add($a, $b = 0) {
    return $a + $b;
    }
    This would allow us to call the function with just one argument (e.g. add(3)), in which case $b would default to 0.Functions can return multiple values by returning an array. For example:

function get_user_info($user_id) {
// Retrieve user data from database
$user = [
“name” => “John Smith”,
“email” => “john@example.com”,
“age” => 30
];

// Return an array containing user info
return [$user[“name”], $user[“email”], $user[“age”]];
}

// Call the function and store the results in variables
list($name, $email, $age) = get_user_info(123);

// Output the results
echo “Name: ” . $name . “<br>”;
echo “Email: ” . $email . “<br>”;
echo “Age: ” . $age . “<br>”;

 

  • In this example, we define a function called “get_user_info” that retrieves user data from a database and returns an array containing the user’s name, email, and age. We then call the function and use the list() function to assign the array values to variables. Finally, we output the results using the echo statement.
  • Functions can be defined in separate files and included in other PHP files using the include() or require() function. For example, if we had a file called “functions.php” containing our “add” function, we could include it in another PHP file like this:

    // Include the functions.php file
    require_once “functions.php”;

    // Call the add() function from functions.php
    $result = add(3, 4);

    // Output the result
    echo $result; // Output: 7

Note that we use require_once instead of include() to ensure that the file is only included once, even if the code calling the include statement is executed multiple times.