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.
addItem($cart, $name, $price): returns the cart with the item added.cheapest($cart): the name of the cheapest item.describeCart($cart):"book: 4.50, pen: 1.20": items in alphabetical order, prices with 2 decimals.