typestar

Associative arrays in PHP

String keys with =>, plus the operators that handle missing ones.

<?php
$stock = ["apples" => 12, "pears" => 4];
$stock["plums"] = 9;

echo $stock["apples"], PHP_EOL;
// ?? supplies a default when the key is missing
echo $stock["kiwis"] ?? 0, PHP_EOL;
echo array_key_exists("pears", $stock) ? "have pears" : "no pears", PHP_EOL;

print_r(array_keys($stock));
echo count($stock), " kinds in stock", PHP_EOL;

How it works

  1. => pairs keys with values; plain assignment adds plums in place.
  2. ?? supplies a default for the missing key instead of a warning.
  3. array_key_exists asks without reading; array_keys lists every key.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
340
Tokens
85
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 68 seconds.

Type this snippet

Step 2 of 3 in Arrays, step 8 of 27 in Language basics.

← Previous Next →

Associative arrays in other languages