PHP array_key_exists
Check whether a saved seat key exists before reading the seat.
A simple example
array_key_exists
- Start with A list containing only A
- Do this Ask for the third item
- Result Outside the list
Syntax
array_key_exists($index, $seats)
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpFind a seat after the coach changes
A bus operator replaces a coach with a smaller one. A passenger's saved seat position now falls outside the new seating list, so the booking screen must ask them to choose again.
<?php
$seats = ['Window', 'Aisle'];
$index = 2;
echo array_key_exists($index, $seats) ? $seats[$index] : 'Choose another seat';
Choose another seat
The saved position is just beyond the two-seat list. The booking desk asks for a replacement seat.
Open the last appointment
A desk offers two appointments and a visitor selects index one. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.
Reject a stale bus selection
An old menu points to index two after the coach list shrinks to two stops. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.
What to watch for
PHP arrays can have gaps in their numeric keys. Comparing the position to count alone can miss a removed key.