Swap Two Numbers in PHP

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 3 Code Examples
Variables & references

What you’ll learn

  • What swapping means in everyday terms (two values trade places).
  • The classic three-step pattern with a $temp variable—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 $temp variable (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.

  • <?php scripts, variables such as $num1, and assignment $a = $b;.
  • For Example 1: parameters written as &$a are 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.

Memory aid

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

Start Before
num1
5
num2
10
temp Holds 5
Why
Save the old num1 before overwriting it.
Done After
num1
10
num2
5

Live preview

Uses the same three-step pattern as the PHP samples. Values stay inside JavaScript safe integers.

Enter integers (try negatives too). Press Swap or Enter in either field.

Live result
Press “Swap” to see before and after values.

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

Pseudocode
procedure swap(a, b):  // a and b name two storage slots
    temp ← a
    a ← b
    b ← temp
1

Function 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
<?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.

2

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
<?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.

3

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
<?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

After swapping, the first variable holds what the second used to hold, and the second holds what the first used to hold. If you start with 5 and 10, you end with 10 and 5.
If you write $a = $b first, you lose the old value of $a before you can copy it into $b. A spare variable called $temp remembers the first value while you move things around.
Plain parameters are passed by value in PHP: the function would only swap its own copies. Adding &amp; makes aliases of the caller's variables, so changes inside the function are visible outside.
Yes. Example 3 on this page uses XOR for integers. Add/subtract patterns also exist but can overflow. Learn the temp version first, then treat XOR as a puzzle trick, not your everyday style.
Each swap is a few assignments: constant time O(1) and constant extra space for one integer.
Swapping 7 and 7 still works; nothing visible changes. With XOR tricks, passing the same variable twice by reference can zero it out, so avoid that pattern and prefer temp when unsure.

🔄 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, 1010, 5
0, 33, 0
-4, 2020, -4
7, 77, 7

Edge cases

Most mistakes come from forgetting why references exist, or from “clever” swaps that overflow.

Copies

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.

Order

Never start with $a = $b alone

You lose the original $a and cannot recover it for $b without a saved copy.

Overflow

Arithmetic swaps

Adding two huge integers can overflow PHP's integer range (PHP switches to float). Stick to $temp unless you control the range.

XOR

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

VersionTimeExtra 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 trickO(1)O(1); watch overflow

Summary

  • Pattern: $temp = $a; $a = $b; $b = $temp; (or reference-parameter versions of the same story).
  • Functions: take &$a style parameters so you edit the caller’s variables.
  • Extras: Example 3 shows XOR without $temp; add/subtract exists too—$temp stays the readable default.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful