PHP Functions

Defining a Function

A function in PHP is a reusable block of code that performs a specific task. Functions help organize your code and avoid repetition.

To define a function, use the function keyword followed by the function name and a pair of parentheses. The code inside the curly braces is the function body.

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

greet();  // Calls the function

In the example above, the function greet() is defined to print a greeting message. When you call greet();, the code inside the function runs and outputs "Hello, world!".

Best Practice: Always define your functions before calling them, and give them clear, descriptive names that indicate their purpose.

Return Values

A function can send back a value to the part of the program that called it using the return statement. This is called a return value.

The returned value can be stored in a variable or used directly in expressions.

function add($a, $b) {
  return $a + $b;
}

$result = add(5, 3);
echo $result;  // 8

In this example, the add() function takes two numbers, adds them, and returns the result. That result is stored in $result and then printed.

Best Practice: Use return values when the function performs a calculation or needs to pass a result back.

Return Values

A return value is the output a function gives back after it finishes running. You use the return keyword to send a value back to the code that called the function.

The returned value can be stored in a variable, printed out, or used in further calculations. If a function doesn't include a return statement, it returns null by default.

function add($a, $b) {
  return $a + $b;
}

$result = add(5, 3);
echo $result;  // 8

In this example, the function add() calculates the sum of two arguments and returns the result. That value is stored in the variable $result and then printed using echo.

Best Practice: Always return a value when your function does a calculation or retrieves data. This helps you reuse the result elsewhere in your program.

Default Parameters

function greet($name = "Guest") {
  echo "Welcome, $name!";
}

greet();         // Welcome, Guest!
greet("Alice");  // Welcome, Alice!

Variable-Length Parameters

function sumAll(...$numbers) {
  return array_sum($numbers);
}

echo sumAll(1, 2, 3, 4);  // 10

... is used to gather multiple arguments into an array.

Function Scope

  • Local: Declared inside function
  • Global: Declared outside (use global keyword)
$x = 10;

function showX() {
  global $x;
  echo $x;
}

Anonymous Functions

$greet = function($name) {
  return "Hi, $name";
};

echo $greet("Bob");

Useful for callbacks or when storing functions in variables.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic