A function is a reusable block of code that you give a name. You write it once, then call it as many times as you need. It is the key to clean, repetition-free code.

Anatomy of a function

  • The function keyword followed by a name.
  • Parameters in brackets (the data you hand over to it).
  • A block of code between curly braces.
  • Often a return that sends back a result.

For example: a function add($a, $b) that does return $a + $b;. You then call it with echo add(2, 3);, which displays 5.

Why use them

  1. Avoid copying and pasting the same code.
  2. Fix a bug in a single place.
  3. Make the program easier to read.

Key point: a function groups a reusable piece of processing. return sends back a value, unlike echo, which displays it.