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
=>pairs keys with values; plain assignment addsplumsin place.??supplies a default for the missing key instead of a warning.array_key_existsasks without reading;array_keyslists every key.
Keywords and builtins used here
array_key_existsarray_keyscountechoprint_r
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.
Step 2 of 3 in Arrays, step 8 of 27 in Language basics.