PHP Functions

In PHP, a function is a block of code that can be reused multiple times in a program. Functions can accept input in the form of arguments, and can return output in the form of a return value.

Here is an example of a simple function that adds two numbers:

function add($x, $y) {
  $sum = $x + $y;
  return $sum;
}

echo add(1, 2); // Outputs 3
echo add(5, 10); // Outputs 15

You can define a function using the ‘function’ keyword, followed by the name of the function and a list of arguments in parentheses. The code to be executed by the function is contained within curly braces.

To call a function, you can use its name followed by a list of arguments in parentheses.

You can also use default values for function arguments to specify a value that will be used if an argument is not passed to the function. For example:

function add($x, $y = 0) {
  $sum = $x + $y;
  return $sum;
}

echo add(1); // Outputs 1
echo add(5, 10); // Outputs 15

In this example, the ‘add()’ function has a default value of 0 for the ‘$y‘ argument, so if ‘$y‘ is not specified when the function is called, it will use the default value of 0.

Here is an example of how you can pass an argument by reference to a function:

function addFive(&$x) {
  $x += 5;
}

$x = 10;
addFive($x);
echo $x; // Outputs 15

In this example, the ‘addFive()’ function accepts an argument ‘$x’ by reference, which means that any changes made to ‘$x’ within the function will be reflected in the original variable.

You can also use the ‘global’ keyword to access global variables within a function. For example:

$x = 10;
$y = 20;

function add() {
  global $x, $y;
  $sum = $x + $y;
  return $sum;
}

echo add(); // Outputs 30

In this example, the ‘add()’ function can access the global variables ‘$x’ and ‘$y’, even though they are not passed as arguments to the function.