๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

PHP Functions

A function is a named block of code that does one job. A program runs the block by calling the function.

A first function

The definition names the function sayHello. The line after the definition calls it, and the greeting prints.

<?php
function sayHello() {
  echo "Hello!\n";
}

sayHello();

Calling a function twice

The same call appears twice. Each call runs the body, so the greeting prints twice.

<?php
function sayHello() {
  echo "Hello!\n";
}

sayHello();
sayHello();

One function, one job

The printSeparator function has one job. It prints a separator line between two other lines.

<?php
function printSeparator() {
  echo "--- Report ---\n";
}

echo "First part\n";
printSeparator();
echo "Second part\n";

Example

<?php
function showTitle() {
  echo "Weekly Report\n";
}

function showLine() {
  echo "------------\n";
}

showTitle();
showLine();
echo "Sales are up\n";
showLine();
echo "End of report\n";

Key points

  • The word function starts a function definition.
  • A definition gives the function a name and holds its body in braces.
  • The definition alone runs nothing.
  • A call runs the function.
  • A call is the function name with a pair of round brackets after it.
  • The same function can be called many times.

In this example, two functions are defined at the top. showTitle prints the title line, and showLine prints a plain line. The calls run in order, so the title, a line, a sentence, a line, and the last sentence print one after another.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What makes the body of a function run?