Functions

Course 1 · Ch 5
Functions: Defining, Parameters, Return Values, and Scope
Packaging reusable logic into named blocks — and the variable-visibility rules that come with them

Every chapter so far has written code directly in the main flow of the script. Functions let you package a block of logic under a name, run it whenever needed (possibly many times, possibly with different inputs), and keep the main script focused on the bigger picture rather than repeated detail.

Defining and Calling a Function

<?php function greet() { echo "Hello there!"; } greet(); // calls the function, runs its body — outputs "Hello there!" greet(); // can be called again, as many times as needed ?>

A function is defined once with the function keyword and a name, then "called" by writing that name followed by parentheses wherever its logic is needed.

Parameters — Passing Values In

<?php function greet($name) { echo "Hello, $name!<br>"; } greet("Philip"); // "Hello, Philip!" greet("Sam"); // "Hello, Sam!" // Default parameter values — used when the argument is omitted function greetWithDefault($name = "Guest") { echo "Welcome, $name!<br>"; } greetWithDefault(); // "Welcome, Guest!" greetWithDefault("Ana"); // "Welcome, Ana!" ?>

Parameters let the same function behave differently depending on what's passed in. A default value ($name = "Guest") makes that parameter optional — if no argument is supplied for it, the default is used instead.

Return Values — Getting a Result Back Out

<?php function addNumbers($a, $b) { return $a + $b; } $total = addNumbers(4, 9); echo $total; // 13 ?>
return immediately exits the function — any code after it never runs
Unlike echo, which just prints output and continues, return hands a value back to wherever the function was called from AND stops the function's execution immediately. Code placed after a return statement inside the same block is unreachable and will never execute.

Type Hints and Return Types — Optional, but Genuinely Useful

<?php function addNumbers(int $a, int $b): int { return $a + $b; } ?>

Adding int before each parameter, and : int after the parentheses, tells PHP exactly what types are expected in and out. This is entirely optional in PHP (unlike strictly-typed languages where it's mandatory), but it documents intent clearly and helps PHP catch type mistakes earlier rather than letting an unexpected type silently cause confusing behaviour deeper in the script.

Variable Scope — Where a Variable "Exists"

<?php $x = 10; // a global-scope variable function tryToChangeX() { $x = 99; // this is a DIFFERENT $x, local to this function only echo $x; // 99 } tryToChangeX(); echo $x; // still 10 — the outer $x was never touched ?>

Every function has its own local scope — variables created inside a function exist only inside that function, completely separate from a same-named variable outside it. This is a deliberate safety feature, not a limitation: it means a function's internal variables can never accidentally clash with or overwrite variables elsewhere in the script.

Global scope $x = 10 function tryToChangeX() $x = 99 separate!
Two completely separate $x variables — the function's local $x has no effect on the global one
global keyword and function arguments are the two real ways data crosses the scope boundary
A function can access an outer variable deliberately by declaring global $x; as its first line — but this is rarely the cleanest approach in practice. Passing the value in as a parameter, and getting a result back via return, is almost always the better, more predictable pattern, and is the approach used throughout this course.

Coding Challenges

Challenge 1

Write a function isEven($number) that returns true if a number is even and false if it's odd (using the % remainder operator from Chapter 4). Call it with a few different numbers and echo the results using var_dump.

📄 View solution
Challenge 2

Write a function calculateRectangleArea($width, $height = 1) with a default height of 1, so it can also be used to calculate the area of a square just by passing one argument. Call it three different ways and echo each result.

📄 View solution
Challenge 3

Create a global variable $counter = 0. Write a function that creates its own local variable also called $counter, sets it to 100, and echoes it. After calling the function, echo the original global $counter to demonstrate it was never affected — add a comment explaining why.

📄 View solution

Chapter 5 Quick Reference

  • function name(params) { } — defines a reusable named block of code
  • Default parametersfunction f($x = "default") makes an argument optional
  • return — hands a value back AND exits the function immediately; code after it never runs
  • echo vs return — echo prints output, return hands back a usable value to the caller
  • Type hints — optional but recommended: function f(int $x): int
  • Scope — variables inside a function are local; they cannot accidentally affect same-named outer variables
  • global keyword — exists, but passing parameters and using return is the cleaner default pattern
  • Next chapter: arrays — indexed, associative, and common array functions