Swap two numbers in PHP

To swap two values, save the first in a temporary variable, assign the second to the first, and then restore the saved value into the second.

A simple example

Exchange two values

  1. Start with a = 1, b = 2
  2. Do this Keep a copy of the first value
  3. Result a = 2, b = 1
Save 1, move 2 into a, then move the saved 1 into b. This preserves both original values.

Swap two presentation slots

  1. Start with Slot 1 for Ada, slot 2 for Sam
  2. Do this Exchange the two assignments
  3. Result Slot 1 for Sam, slot 2 for Ada
Keeping one assignment while moving the other prevents either student from disappearing from the schedule.
  1. Temporary variable
  2. Arithmetic operation
  3. Exclusive OR operation (i.e. XOR)

The arithmetic examples assume the intermediate results fit the numeric type. Multiplication followed by division also requires nonzero divisors. XOR swapping applies to integers stored in distinct variables.