Lesson 4 of 8 · 9 min

Arrays

Indexed arrays

$fruits = ["mango", "banana"];
$fruits[] = "guava";          // add to the end
echo $fruits[0];              // mango (counting from 0)
echo count($fruits);          // 3
in_array("banana", $fruits);  // true

Associative arrays

The same [...] syntax with keys makes a dictionary:

$capitals = [
    "Zimbabwe" => "Harare",
    "Mauritius" => "Port Louis",
];
$capitals["Kenya"] = "Nairobi";
echo $capitals["Zimbabwe"];             // Harare
array_key_exists("Ghana", $capitals);   // false
unset($capitals["Kenya"]);              // remove

Sorting

PHP has a sorting function for each need. They sort the array in place:

Function Sorts by Keeps keys?
sort / rsort value no
asort / arsort value yes
ksort / krsort key yes

Arrays are copied when passed to a function, so sorting inside a function does not change the caller's array.

Handy helpers: array_keys, array_values, array_key_first, implode(", ", $list) (join into a string), explode(",", $text) (split), number_format(4.5, 2) gives "4.50".

Your task

A cart is an associative array of item name to price.

  1. addItem($cart, $name, $price): returns the cart with the item added.
  2. cheapest($cart): the name of the cheapest item.
  3. describeCart($cart): "book: 4.50, pen: 1.20": items in alphabetical order, prices with 2 decimals.
index.php
<?php
function addItem($cart, $name, $price) {
}

function cheapest($cart) {
}

function describeCart($cart) {
}

$cart = addItem(["pen" => 1.2], "book", 4.5);
echo describeCart($cart), "\n";

PHP 8.4 runs right here in your browser. The first run downloads about 12 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…