Functions

Functions are an essential part of any programming language, including PHP. A function is a block of code that performs a specific task and can be used repeatedly throughout your code. Functions help to break up your code into smaller, more manageable pieces, making your code easier to read, test, and maintain.

Here's an example of a basic function in PHP:

function helloWorld() {
  echo "Hello, world!";
}

This function is called helloWorld(), and it simply outputs the string "Hello, world!" to the screen using the echo statement.

You can call this function in your code by simply writing the function name followed by parentheses:

helloWorld(); // Outputs "Hello, world!"

Functions can also accept parameters, which are values that you pass into the function for it to use in its calculations. Here's an example of a function that accepts two parameters:

function addNumbers($num1, $num2) {
  $sum = $num1 + $num2;
  echo "The sum of $num1 and $num2 is $sum";
}

This function is called addNumbers(), and it accepts two parameters: $num1 and $num2. These two parameters are then used to calculate the sum of the two numbers, which is stored in a variable called $sum. The function then outputs the result using the echo statement.

You can call this function in your code by passing in two values for $num1 and $num2:

addNumbers(5, 10); // Outputs "The sum of 5 and 10 is 15"

Functions can also return values using the return statement. Here's an example of a function that calculates the area of a rectangle and returns the result:

function calculateArea($length, $width) {
  $area = $length * $width;
  return $area;
}

This function is called calculateArea(), and it accepts two parameters: $length and $width. These two parameters are used to calculate the area of the rectangle, which is stored in a variable called $area. The function then returns the value of $area using the return statement.

You can call this function in your code and store the result in a variable:

$rectangleArea = calculateArea(5, 10);
echo "The area of the rectangle is $rectangleArea"; // Outputs "The area of the rectangle is 50"

Functions can also have default parameter values, which are used if no value is passed in for a particular parameter. Here's an example of a function that has default parameter values:

function greetUser($name = "Guest") {
  echo "Hello, $name!";
}

This function is called greetUser(), and it accepts one parameter: $name. If a value is passed in for $name, the function will output "Hello, [name]!". If no value is passed in for $name, the function will output "Hello, Guest!".

You can call this function in your code without passing in a value for $name:

phgreetUser(); // Outputs "Hello, Guest!"

Or you can pass in a value for $name:

greetUser("John"); // Outputs "Hello, John!"

Last updated