PHP Indexed array access
Read one name from an ordered roster after checking its length.
A simple example
Indexed array access
- Start with A, B, C
- Do this Read the second element
- Result B
Syntax
$names[$index]
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpRead the second name on the pickup roster
A teacher calls children in their recorded pickup order. The office asks for the second name on the roster, so the teacher checks that the list contains at least two entries before reading it.
<?php
$names = ['Asha', 'Mira', 'Sam'];
if (array_key_exists(1, $names)) {
echo $names[1];
}
Mira
Mira occupies the second position on the three-person roster.
Prepare the next workshop roster
A teacher reads a workshop roster in arrival order. Who or what occupies the second position? Count from the front of the list.
Work from the delivery round
A courier has three labelled stops in route order. Who or what occupies the second position? Count from the front of the list.
What to watch for
A PHP array may have gaps in its keys. Test for the required key when the list did not originate as a dense sequence.