LEARN TO CODE | PHP | 01 SERVER-SIDE FOUNDATIONS
01.4 Functions and arrays
Organise reusable calculations in functions and generate repeated page content from arrays of related data.
01 | WHY REUSE A TASK?
Use the local development server from 01.1 . Save each complete example in its own .php file inside myWebsite, keep the server running and open its URL through http://127.0.0.1:8000/. Save changes and refresh the browser.
Short PHP-only examples can also be served as files: their output appears as the response body. Each example is independent unless stated otherwise. Browser HTML view, not the editor’s source view, shows the result.
A page showing several clubs needs the same calculation repeatedly: capacity minus members. A function gives that task a name, inputs and a result so we can use it without rewriting the logic.
An array lets us keep several clubs together. Combining arrays and functions makes it easier to generate a consistent page from data.
02 | DEFINE AND CALL A FUNCTION
<?php
function placesLeft(int $capacity, int $members): int
{
return $capacity - $members;
}
$remaining = placesLeft(12, 10);
echo $remaining;
EXPECTED OUTPUT
2
function defines the task; placesLeft is its name. $capacity and $members are parameters: local names for incoming values. In placesLeft(12, 10), 12 and 10 are the supplied arguments.
The int annotations describe the intended parameter and return types. PHP can coerce some scalar arguments in its default mode; these examples deliberately pass integer values. Strict typing is a later refinement, not a substitute for validating real input.
03 | RETURN IS DIFFERENT FROM ECHO
return passes a value back to the caller and finishes that function execution. echo sends output into the response. A function returning 2 does not automatically display 2.
Returning the calculation lets the caller display it, compare it or combine it with another value. That is more flexible than embedding a paragraph inside every calculation.
<?php
function doubleValue(int $value): int
{
return $value * 2;
}
$result = doubleValue(5);
echo '<p>' . $result . '</p>';
EXPECTED OUTPUT
10
04 | LOCAL VARIABLES STAY WITH THE FUNCTION
<?php
function greeting(string $name): string
{
$message = 'Hello, ' . $name;
return $message;
}
echo htmlspecialchars(greeting('Maya'), ENT_QUOTES, 'UTF-8');
$name and $message are local to this function execution. They are not automatically available as caller variables. Pass needed data in and return the result instead of relying on hidden global state.
Keep a function focused. A name like placesLeft describes its responsibility better than a vague name such as doStuff.
05 | INDEXED ARRAYS HOLD A LIST
<?php
$clubs = ['Robotics', 'Art', 'Chess'];
echo $clubs[0];
$clubs[] = 'Coding';
echo '<p>' . count($clubs) . '</p>';
EXPECTED OUTPUT
Robotics 4
For this newly created list, keys are 0, 1 and 2. $clubs[0] retrieves Robotics. Appending with [] adds Coding using the next integer key.
PHP arrays are ordered maps, so they can support both integer and string keys. Removing items can leave gaps in integer keys; do not assume every PHP array is always a continuous zero-based list.
06 | FOREACH VISITS THE VALUES
<?php
$clubs = ['Robotics', 'Art', 'Chess'];
echo '<ul>';
foreach ($clubs as $club) {
echo '<li>' . htmlspecialchars($club, ENT_QUOTES, 'UTF-8') . '</li>';
}
echo '</ul>';
EXPECTED OUTPUT
• Robotics • Art • Chess
On each iteration, $club holds the next array value. It is a chosen local variable name, not a reserved word. The body outputs one li element per value.
The fixed ul tags create one list around the repeated content. Escaping each text value keeps it as text in the HTML response.
07 | ASSOCIATIVE ARRAYS USE NAMED KEYS
<?php
$club = [
'name' => 'Robotics',
'capacity' => 12,
'members' => 10,
];
echo htmlspecialchars($club['name'], ENT_QUOTES, 'UTF-8');
echo '<p>' . ($club['capacity'] - $club['members']) . '</p>';
EXPECTED OUTPUT
Robotics 2
The => associates a key with a value. $club['capacity'] looks up a named entry rather than numeric position. The array can contain values of different types.
A missing key is not a valid known value. Check the structure you expect; a fixed dataset with consistent keys is a good starting point before handling outside data.
08 | LOOP OVER KEYS AND VALUES
<?php
$fees = ['Robotics' => 15, 'Art' => 8, 'Chess' => 0];
foreach ($fees as $clubName => $fee) {
echo '<p>' . htmlspecialchars($clubName, ENT_QUOTES, 'UTF-8');
echo ': ' . $fee . '</p>';
}
EXPECTED OUTPUT
Robotics: 15 Art: 8 Chess: 0
The first foreach variable receives the key; the second receives its value. Zero is a meaningful free fee, not a missing entry.
Choose clear names so it is obvious whether you are using an array’s labels or its stored values.
09 | NESTED ARRAYS REPRESENT RECORDS
<?php
$clubs = [
['name' => 'Robotics', 'capacity' => 12, 'members' => 10],
['name' => 'Art', 'capacity' => 10, 'members' => 6],
];
echo htmlspecialchars($clubs[1]['name'], ENT_QUOTES, 'UTF-8');
EXPECTED OUTPUT
Art
The outer array is a list of records. Each inner associative array describes one club. First select the record at index 1, then its name entry.
This is in-memory data prepared in the PHP request. It is not a database merely because it looks like rows, and edits to it are not automatically saved between requests.
10 | COMBINE FUNCTIONS AND DATA
TRY IT YOURSELF
Using a placesLeft function and two club records, output each name and its calculated remaining places.
Reveal guidance
<?php
function placesLeft(int $capacity, int $members): int
{
return $capacity - $members;
}
$clubs = [
['name' => 'Robotics', 'capacity' => 12, 'members' => 10],
['name' => 'Art', 'capacity' => 10, 'members' => 6],
];
foreach ($clubs as $club) {
$remaining = placesLeft($club['capacity'], $club['members']);
echo '<p>' . htmlspecialchars($club['name'], ENT_QUOTES, 'UTF-8');
echo ': ' . $remaining . ' places</p>';
}
Expect Robotics: 2 places and Art: 4 places. Do not paste a second definition of the same function into a file that already declares it.
11 | DESIGN A HELPER FOR HTML TEXT
<?php
function escapeHtml(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
echo '<p>' . escapeHtml('Art & Design') . '</p>';
The helper centralises HTML text escaping so templates stay readable. It is not a general-purpose sanitizer for every output context.
Next, complete the section challenges and build a small club listing. Then move to reusable includes, forms and sessions.
KEEP LEARNING
Previous page 01 Server-side foundations: challenges
References: PHP development server · Types · Arrays · HTML text escaping