PHP Associative array assignment
Update a shelf count and retrieve it using the product label.
A simple example
Associative array assignment
- Start with A = 1
- Do this Store 2 at key A
- Result A = 2
Syntax
$stock[$key] = $count
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpUpdate the count for a shelf label
A shop keeps one inventory entry for each shelf label. After a second delivery arrives, the clerk replaces the old tea count and looks up the current total using the same label.
<?php
$stock = ['Tea' => 3];
$stock['Tea'] = 7;
echo $stock['Tea'];
7
Updating the Tea key changes the recorded count from three to seven.
Revise a locker assignment
A rental desk moves the green key from locker 6 to locker 9. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?
Correct a menu price
A café changes its soup price after reprinting the menu. The operator assigns the new value to the existing key and reads it back. Which value does the key now hold?
What to watch for
A numeric-looking string key can be converted to an integer key in a PHP array.