Library contents

PHP unset after owner comparison

Release a locker after checking that its current owner is the student returning it.

A simple example

unset after owner comparison

  1. Start with A = 1
  2. Do this Remove A if its value is 1
  3. Result A is absent
The stored value matches the expected value, so the removal proceeds.

Syntax

PHP syntax
unset($claims[$key])
Run these examples in PHP

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

php lesson.php

Release a locker only for its recorded owner

A school uses locker numbers as keys and student names as values. When Mira returns her locker, the desk clears the assignment only if the current register still names Mira.

From the program$claims = ['L2' => 'Mira']
ResultReleased
lesson.php
<?php
$claims = ['L2' => 'Mira'];
if (($claims['L2'] ?? null) === 'Mira') {
    unset($claims['L2']);
    echo 'Released';
}
Output
Released

Locker L2 belongs to Mira, so the register accepts the return.

Advertisements

Return a locker key

A locker has a single claim and its registered holder returns the key. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?

GivenHolder Pia · claimant Pia
Worked result0

Keep a reserved headset

A different student tries to release the only headset claim. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?

GivenHolder Rae · claimant Sam
Worked result1

What to watch for

Use strict comparison when identifiers of different types should remain distinct.

Documentation for unset after owner comparison