php language basics

Language Recap and Exercises

This recap is a checkpoint. You should now be able to write a small PHP script that uses variables, arrays, strings, functions, control flow, type declarations, exceptions, and includes without needing to look up every line.

The goal is not to know every PHP feature. The goal is to combine the beginner features deliberately and explain the result.

A Small Complete Script

PHP example
<?php

declare(strict_types=1);

function formatPrice(int $cents): string
{
    if ($cents < 0) {
        throw new InvalidArgumentException('Price cannot be negative.');
    }

    return '£' . number_format($cents / 100, 2);
}

$products = [
    ['name' => 'Notebook', 'price_cents' => 1299],
    ['name' => 'Pen', 'price_cents' => 199],
];

foreach ($products as $product) {
    echo $product['name'] . ': ' . formatPrice($product['price_cents']) . "\n";
}

// Prints:
// Notebook: £12.99
// Pen: £1.99

This script is small, but it combines several important habits: typed helper functions, array records, a loop, validation, a return value, and string output.

What To Check In Your Own Code

Before moving on, review your beginner scripts with these questions:

  • Are values named clearly enough to show their unit or purpose?
  • Does each function have a small job?
  • Are invalid values handled deliberately?
  • Are optional array keys read with a clear fallback or check?
  • Is output produced at the edge of the script, not hidden inside every helper?
  • Can you run the script and predict the output?

What Comes Next

The remaining Track 01 project lessons turn these basics into small scripts: a CLI receipt calculator, a data-cleaning script, and a multi-file script. Those projects should feel like practice with the same concepts, not a completely new language.

Practice

Task: Price Recap

Task

Write a formatPrice(int $cents): string function that returns a price like £12.99.

Use it to print prices for two products in an array.

Show solution

Solution

PHP example
<?php

declare(strict_types=1);

function formatPrice(int $cents): string
{
    return '£' . number_format($cents / 100, 2);
}

$products = [
    ['name' => 'Notebook', 'price_cents' => 1299],
    ['name' => 'Pen', 'price_cents' => 199],
];

foreach ($products as $product) {
    echo $product['name'] . ': ' . formatPrice($product['price_cents']) . "\n";
}

// Prints:
// Notebook: £12.99
// Pen: £1.99

Explanation

The helper handles formatting. The loop handles the product list and output.

Task: Predict Recap Output

Task

Before running the code, predict the output.

PHP example
<?php

declare(strict_types=1);

function label(array $product): string
{
    $stock = ($product['in_stock'] ?? false) ? 'available' : 'unavailable';

    return $product['name'] . ' is ' . $stock;
}

$products = [
    ['name' => 'Notebook', 'in_stock' => true],
    ['name' => 'Pen'],
];

foreach ($products as $product) {
    echo label($product) . "\n";
}
Show solution

Solution

PHP example
<?php

declare(strict_types=1);

function label(array $product): string
{
    $stock = ($product['in_stock'] ?? false) ? 'available' : 'unavailable';

    return $product['name'] . ' is ' . $stock;
}

$products = [
    ['name' => 'Notebook', 'in_stock' => true],
    ['name' => 'Pen'],
];

foreach ($products as $product) {
    echo label($product) . "\n";
}

// Prints:
// Notebook is available
// Pen is unavailable

Explanation

The first product has in_stock set to true. The second product is missing the key, so ?? false makes it unavailable.

Task: Build Validation Recap

Task

Write requireProductName(array $product): string.

The function should:

  • read name from the product array;
  • trim it;
  • throw InvalidArgumentException when it is missing or empty;
  • return the cleaned name.

Call it with ['name' => ' Mug '] and print the result.

Show solution

Solution

PHP example
<?php

declare(strict_types=1);

function requireProductName(array $product): string
{
    $name = trim((string) ($product['name'] ?? ''));

    if ($name === '') {
        throw new InvalidArgumentException('Product name is required.');
    }

    return $name;
}

echo requireProductName(['name' => '  Mug  ']) . "\n";

// Prints:
// Mug

Explanation

The function treats the array as a boundary: read the optional key, normalize it, validate it, then return a clean string.