PHP array_splice for insertion
Insert a group of new stops before a known position on a route.
A simple example
array_splice for insertion
- Start with A, C
- Do this Insert B between them
- Result A, B, C
Syntax
array_splice($stops, $index, 0, $extra)
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpInsert two pickup stops before the depot
A shuttle normally travels straight from the school to the depot. The dispatcher adds two afternoon pickups and needs them to appear in the supplied order before the final stop.
<?php
$stops = ['School', 'Depot'];
array_splice($stops, 1, 0, ['Hall', 'Pool']);
echo implode(', ', $stops);
School, Hall, Pool, Depot
Hall and Pool are inserted between the school and the depot in pickup order.
Extend a reading list
A class has chosen one novel and adds two more titles. The desk adds the new entries after the existing ones. Read the resulting sequence in its recorded order.
Update an equipment checklist
A technician adds the final item after packing two pieces of equipment. The desk adds the new entries after the existing ones. Read the resulting sequence in its recorded order.
What to watch for
A length of zero inserts without removing. Numeric keys are renumbered.