- num1
- 5
- num2
- 10
Swap Two Numbers in PHP
What you’ll learn
- What swapping means in everyday terms (two values trade places).
- The classic three-step pattern with a
$tempvariable—and why you need it. - A version with references (
&$a) so a function can change variables in the caller, plus a version that stays entirely at the top level of your script. - An XOR pattern that swaps without any
$tempvariable (integers only, with important caveats). - A live preview, short notes on arithmetic swaps, and interview-style pitfalls.
Overview
You have two labeled boxes, $num1 and $num2. Swapping means: whatever was inside the first box moves to the second, and whatever was in the second moves to the first. A third spare box, $temp, holds one value for a moment so nothing gets erased too early.
Three code examples
Example 1: references and $temp. Example 2: same idea inline in your script. Example 3: XOR swap with no extra variable.
Live preview
Type two integers and press Swap to see “before” and “after” lines that match the PHP idea.
Extras you may hear in class
After Example 3, the notes recap why add/subtract swaps can overflow and why temp stays the default in real code.
Prerequisites
You should know what a variable is and how to print values with echo.
<?phpscripts, variables such as$num1, and assignment$a = $b;.- For Example 1: parameters written as
&$aare passed by reference so the function edits the caller's variables. If that is new, read Example 2 first.
What does swapping do?
After a correct swap, the first variable shows the value the second used to have, and the second shows what the first used to have. Order matters in sorting; swapping is the smallest “exchange” step.
Picture two full cups. You cannot pour both into each other at once without spilling. So you use a third empty cup ($temp) to hold one drink while you move the other.
Why references inside a function?
In PHP, when you pass $x into a function without &, the function receives a copy of the value (for simple types). Swapping copies inside the helper does not change $num1 and $num2 in the caller. Parameters written as &$a and &$b are aliases: assignments to $a and $b update the original variables.
swapNumbers($num1, $num2) with a signature like function swapNumbers(&$a, &$b) says “work on the caller's real variables, not disposable copies.”
Trace on paper
- Why
- Save the old
num1before overwriting it.
- num1
- 10
- num2
- 5
Live preview
Uses the same three-step pattern as the PHP samples. Values stay inside JavaScript safe integers.
Algorithm
Goal: exchange the values in two integer variables using a temporary third integer.
Copy first into temp
$temp = $a; (same idea when $a is a reference parameter).
Move second into first
$a = $b;.
Move saved value into second
$b = $temp;.
📜 Pseudocode
procedure swap(a, b): // a and b name two storage slots
temp ← a
a ← b
b ← tempFunction with references (classic interview style)
swapNumbers uses reference parameters (&$a, &$b) so the swap survives after the function returns. PHP passes those aliases when you call swapNumbers($num1, $num2).
<?php
function swapNumbers(int &$a, int &$b): void
{
$temp = $a;
$a = $b;
$b = $temp;
}
$num1 = 5;
$num2 = 10;
echo "Before swapping: num1 = $num1, num2 = $num2\n";
swapNumbers($num1, $num2);
echo "After swapping: num1 = $num1, num2 = $num2\n";
?>Explanation
$temp = $a;Save the first value. Because $a is a reference parameter, this reads the caller's first variable.
$a = $b; $b = $temp;Finish the exchange. First overwrites the first variable with the second value, then restores the saved value into the second variable.
All in one script (no references needed)
Same three moves, but the variables are ordinary $num1 and $num2 at the top level of your script. This is often the easiest version on day one of PHP.
<?php
$num1 = 5;
$num2 = 10;
echo "Before swapping: num1 = $num1, num2 = $num2\n";
$temp = $num1;
$num1 = $num2;
$num2 = $temp;
echo "After swapping: num1 = $num1, num2 = $num2\n";
?>Explanation
When everything lives in one scope, plain assignments already touch the real variables—no reference parameters required.
Without any temp variable (XOR, integers only)
Three XOR assignments shuffle bits so the values trade places without a third integer variable. This only works cleanly for integer types where bitwise XOR is defined. The early if ($a === $b) return; skips work when both values are already equal. Important: do not pass the same variable twice (for example swapXor($x, $x)); both parameters would alias one storage and the XOR steps can wipe the value to 0.
<?php
function swapXor(int &$a, int &$b): void
{
if ($a === $b) {
return;
}
$a ^= $b;
$b ^= $a;
$a ^= $b;
}
$num1 = 5;
$num2 = 10;
echo "Before swapping: num1 = $num1, num2 = $num2\n";
swapXor($num1, $num2);
echo "After swapping: num1 = $num1, num2 = $num2\n";
?>Explanation
^= is XOR-then-assign. Each step mixes the two values; after three applications the bits end up exchanged. You do not need to memorize the proof for interviews—just know it is a clever integer trick, not a replacement for $temp in most team code.
if ($a === $b) return;Equal-values shortcut. When both integers already match, swapping does nothing useful. This does not detect PHP alias edge cases; never call swapXor($x, $x).
$a ^= $b; $b ^= $a; $a ^= $b;No spare variable. Only works for types where bitwise XOR behaves as expected (typically integers). For floats or strings, stick to $temp.
Other tricks (read after you know temp)
XOR swap. Full program in Example 3. Prefer $temp for readability unless a style guide says otherwise.
Add/subtract swap. Ideas such as $a = $a + $b; $b = $a - $b; $a = $a - $b; can overflow PHP integers for huge values. Prefer $temp for correctness and clarity.
Interview: show the reference version first; mention that copies inside a naive function swap($x, $y) without & would not change the caller's variables.
❓ FAQ
🔄 Input / output examples
Each sample prints two lines (before and after). Replace the literals or read from input with trim(fgets(STDIN)) (CLI) or $_GET/$_POST on the web—then validate before swapping.
| num1, num2 (before) | After swap |
|---|---|
| 5, 10 | 10, 5 |
| 0, 3 | 3, 0 |
| -4, 20 | 20, -4 |
| 7, 7 | 7, 7 |
Edge cases
Most mistakes come from forgetting why references exist, or from “clever” swaps that overflow.
function swap($x, $y) without &
Swaps only the local copies; the caller's variables never change. Use reference parameters or do the swap directly in the same scope.
Never start with $a = $b alone
You lose the original $a and cannot recover it for $b without a saved copy.
Arithmetic swaps
Adding two huge integers can overflow PHP's integer range (PHP switches to float). Stick to $temp unless you control the range.
Same variable twice (XOR)
Calling the XOR version as swapXor($x, $x) aliases both references to one storage and can wipe the value to 0. Avoid that call pattern entirely.
⏱️ Time and space complexity
| Version | Time | Extra space |
|---|---|---|
| Temp swap (Examples 1 & 2) | O(1) | O(1) (one integer) |
| XOR swap (Example 3) | O(1) | O(1) (no extra variable) |
| Add/subtract trick | O(1) | O(1); watch overflow |
Summary
- Pattern:
$temp = $a; $a = $b; $b = $temp;(or reference-parameter versions of the same story). - Functions: take
&$astyle parameters so you edit the caller’s variables. - Extras: Example 3 shows XOR without
$temp; add/subtract exists too—$tempstays the readable default.
Swapping two values is a tiny step inside bigger ideas such as sorting (for example bubble sort compares and swaps neighbors). The three-line pattern with a temp variable is the clearest way to explain what “exchange” means to a computer.
8 people found this page helpful
