PHP ยท Chapter 17 of 44

PHP Functions

A function is a reusable block of code that performs a specific task. PHP has many built-in functions, and you can also define your own using the function keyword.

Functions help you avoid repeating code, make programs easier to read, and let you organize logic into small, testable pieces. A function only runs when it is called.

Syntax
function myFunction($param) {
  // code
  return $value;
}

Defining and calling functions

A function is defined with the function keyword, a name, and parentheses for parameters. It is executed by calling its name followed by parentheses.

Returning values

The return statement sends a value back to the code that called the function and immediately ends the function's execution.

Example 1 (php)
<?php
  function greet($name) {
    return "Hello, $name!";
  }
  echo greet("Amy");
?>
Output
Hello, Amy!

The function accepts one parameter and returns a greeting string built with it.

Example 2 (php)
<?php
  function add($a, $b) {
    return $a + $b;
  }
  echo add(3, 4);
?>
Output
7

add() returns the sum of its two parameters, which is then echoed.

Key points

  • Functions are defined using the function keyword.
  • Functions can accept parameters and return values.
  • A function must be called to execute its code.
  • return both sends back a value and ends the function.
๐Ÿ’ก Note: Give functions clear, verb-based names like calculateTotal() so their purpose is obvious at a glance.

๐Ÿ“ Quick Quiz

1. Which keyword defines a function in PHP?

2. What does return do?

3. When does a function's code run?