Library contents

PHP Array element replacement

Replace one stop at a known position while preserving the rest of the route.

A simple example

Array element replacement

  1. Start with A, B
  2. Do this Replace the second item with C
  3. Result A, C
Replacing one element keeps the number of elements at two.

Syntax

PHP syntax
$stops[$index] = $newStop
Run these examples in PHP

Save one example at a time as lesson.php. Use PHP 8.2 or later.

php lesson.php

Correct the second stop on a shuttle route

A dispatcher spots an outdated address at the second stop on today's shuttle route. The position on the schedule is correct, so only the destination at that position should change.

From the program$stops = ['School', 'Park']
ResultHarbor
lesson.php
<?php
$stops = ['School', 'Park'];
$stops[1] = 'Harbor';
echo $stops[1];
Output
Harbor

The second stop changes from Park to Harbor.

Advertisements

Correct a lab register

A student signed the lab sheet with a nickname. The second entry must be corrected in place. Which value occupies that position after the change?

GivenAda · Kit → replace Kit with Kiran
Worked resultKiran

Change the next stop

The shuttle cannot use the quay this morning. The second entry must be corrected in place. Which value occupies that position after the change?

GivenSchool · Quay → replace Quay with Pier
Worked resultPier

What to watch for

Assignment creates a new key when it is absent. Check membership if this operation must only replace a stop.

Documentation for Array element replacement