exercises and solutions

Array/string exercises

Practical Example

PHP example
<?php

$orders = [
    ['id' => 1, 'total' => 1250],
    ['id' => 2, 'total' => 800],
];

$totals = array_column($orders, 'total');
$grandTotal = array_sum($totals);

echo 'Grand total: ' . $grandTotal . PHP_EOL;

// Prints:
// Grand total: 2050

Array and string exercises should practise extracting columns, filtering rows, formatting labels, and producing a small expected output.

Do not stop at appending one value. Include missing keys, empty lists, duplicate values, or nested rows where the selected API has an edge case.

Practice

Format Active Product Labels
Show solution

Filter with array_filter(), then loop through the remaining products and format each label with strtoupper(). An empty list should print nothing and should not trigger an undefined-offset warning.

This combines filtering, nested-key lookup, string transformation, and output formatting.

Index Orders By ID

Given a list of orders with id, status, and total_pence, build an array keyed by order ID. Print the total for one known ID and a clear message for a missing ID.

Show solution

Loop through the orders and assign $ordersById[$order['id']] = $order. Read a known order through its key and use array_key_exists() or isset() deliberately for the missing branch.

This mirrors a common application task: reshape a list once when several later lookups need direct access by identifier.