Swap Two Numbers in PHP

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Basics

What You’ll Learn

Swapping exchanges two variables so each holds the other’s old value: a=5, b=10 becomes a=10, b=5. You will use a temp variable, PHP’s [$a, $b] = [$b, $a], and an optional XOR trick for integers — plus a live preview and worked examples.

Temp Variable

Classic

Save, overwrite, restore.

List Destructuring

[$a, $b] = [$b, $a]

The compact everyday PHP swap.

XOR Trick

Integers

Interview curiosity, not style.

No Data Loss

Order

Save before you overwrite.

Live Preview

Try 5 & 10

Swap custom integers instantly.

O(1)

All variants

Constant time and space.

Introduction

Swapping means exchanging the values of two variables without losing either one. If you write a = b first, the old a is gone forever — that is why beginners learn a temporary holder.

In PHP you can skip the explicit temp with list destructuring: [$a, $b] = [$b, $a]. Interviews still like the classic three-step swap because it transfers to C, Java, and sorting algorithms.

Why it matters?

Swap is a building block for sorting, partitioning, and many in-place algorithms.

Key Highlights

Save First

temp holds a copy.

List swap

[$a, $b] = [$b, $a]

XOR Caveat

Integers only.

Equal OK

7, 7 stays 7, 7.

In short: exchange values without losing either — prefer [$a, $b] = [$b, $a] or $temp in PHP.

📝 Problem & Approach

Given two variables, exchange their values so each holds what the other used to hold.

php
// Before: $a = 5,  $b = 10
// After:  $a = 10, $b = 5

Inputs & Outputs

ItemTypeDescription
a, bany / intValues to exchange (XOR needs ints).
Resultsame typesa holds old b; b holds old a.
tempsame as aOptional holding spot.

Minimal workflow

Pseudocode
$temp = $a
$a = $b
$b = $temp

Method comparison

MethodIdeaNotes
Temp variableSave, overwrite, restoreUniversal across languages
List destructuring[$a, $b] = [$b, $a]Compact PHP style
XORa ^= b; b ^= a; a ^= bIntegers; interview trick

⚡ Quick Reference

GoalPattern
Temp save$temp = $a;
Overwrite$a = $b;
Restore$b = $temp;
List swap[$a, $b] = [$b, $a];
XOR (ints)$a ^= $b; $b ^= $a; $a ^= $b;
Equal valuesSwap still correct; no visible change

📋 Temp vs List vs XOR

Same result — different packaging.

Temp
$temp = $a

Clearest cross-language idea

List
[$a, $b] = [$b, $a]

Everyday compact PHP style

XOR
$a ^= $b

Integers only; less readable

Wrong
a = b first

Loses the old a

Context

When This Problem Shows Up

Reach for a swap whenever two values need to trade places in place.

  1. Interview basics

    First assignment / memory drill.

  2. Sorting steps

    Bubble / selection / partition swaps.

  3. List elements

    arr[i], arr[j] = arr[j], arr[i]

  4. Cross-language interviews

    Temp swap proves shared concepts.

  5. Not for XOR on floats

    Stick to temp or list swap then.

Key benefit: one tiny idea — save before overwrite — that shows up in almost every in-place algorithm.

🔮 Live Preview

Enter two integers and swap them with a temporary variable.

Two integers in JavaScript safe integer range.

Live result
Press “Swap”.

Examples Gallery

Three complete PHP programs — temp variable, list destructuring, and XOR for integers. Click View Output to reveal sample console results.

📚 Getting Started

The classic three-step swap that works in almost every language.

Example 1 — Swap Using Temp Variable

Save the first value, overwrite it, then restore into the second variable.

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

How It Works

$temp keeps 5 while $num1 becomes 10. Then $num2 receives the saved 5.

⚡ The PHP Way

List destructuring does the same exchange in one line.

Example 2 — Swap Using List Destructuring

Compact everyday style in PHP. The right-hand side builds a temporary array first.

php
<?php
$num1 = 5;
$num2 = 10;

echo "Before swapping: num1 = $num1, num2 = $num2\n";
[$num1, $num2] = [$num2, $num1];
echo "After swapping: num1 = $num1, num2 = $num2\n";
?>

How It Works

PHP evaluates [$num2, $num1] first, then unpacks into $num1 and $num2. No explicit $temp name is needed.

Example 3 — Swap Without Temp (XOR Trick)

Works for integers. Prefer temp or list swap in real PHP code; keep XOR as an interview curiosity.

php
<?php
$a = 5;
$b = 10;

if ($a !== $b) {
    $a ^= $b;
    $b ^= $a;
    $a ^= $b;
}

echo "After swapping: a = $a, b = $b\n";
?>

How It Works

Three XOR steps rearrange the bit patterns so $a and $b trade places. The $a !== $b guard is a good habit; never XOR-swap the same variable with itself by reference.

🧠 How the Temp Swap Works

1

$temp = $a

Save the first value.

Hold
2

$a = $b

Copy the second into the first.

Overwrite
3

$b = $temp

Restore the saved value into b.

Restore
=

Values exchanged

Neither original was lost.

🔎 Worked Walkthrough — 5 and 10

Follow the temp variable through each assignment.

Stepabtemp
start510
temp = a5105
a = b10105
b = temp1055

If you assign a = b first without saving, the original 5 disappears.

Use Cases

Where swaps show up beyond the interview prompt.

1. Interview Warm-ups

Assignment and memory basics.

Example: temp swap of 5, 10.

2. Sorting Algorithms

Bubble and selection swaps.

Example: adjacent pairs.

3. List Elements

arr[i], arr[j] = arr[j], arr[i]

Example: in-place reorder.

4. Partition Steps

Quicksort-style exchanges.

Example: pivot swaps.

5. Teaching Memory

Why overwrite order matters.

Example: walkthrough table.

6. Next: Triangular

Continue the interview chain.

Example: related CTA.

Pro Tip: say “save before overwrite” before you write the three lines.

Advantages

Why learning all three approaches is useful.

  1. 1. Temp Is Portable

    Same idea in C, Java, JS, and more.

  2. 2. List Is Readable

    One line, hard to get wrong in PHP.

  3. 3. Constant Cost

    O(1) time and space for all variants.

  4. 4. XOR Shows Bit Tricks

    Useful trivia once you know the readable form.

Pro Tip: lead with temp or list swap; mention XOR only if asked about “without a temp”.

Usage Tips

Small habits that keep swap solutions interview-ready.

  1. 1. Save Before Overwrite

    Never a = b as the first step alone.

  2. 2. Prefer List Swap in PHP

    [$a, $b] = [$b, $a] for compact production code.

  3. 3. Print Before and After

    Makes demos and debugging clearer.

  4. 4. Keep XOR Optional

    Integers only; mention readability cost.

  5. 5. Test Equals

    7, 7 should remain 7, 7.

Pro Tip: sanity-check (5, 10), (7, 7), and (-4, 20) — if those three work, you are solid.

Common Pitfalls

Mistakes that commonly break swap programs.

  1. 1. Overwriting Too Soon

    Writing a = b without saving a.

    → Use temp or list destructuring.

  2. 2. XOR on Non-Integers

    Floats and strings do not XOR.

    → Use temp or list instead.

  3. 3. Incomplete XOR Chain

    Missing one of the three ^= steps.

    → Prefer [$a, $b] = [$b, $a] or $temp in PHP.

  4. 4. Thinking Equals Is Broken

    Expecting failure when a == b.

    → Swap is still correct.

  5. 5. Forcing XOR in Production

    Clever but harder to maintain.

    → Use the readable form.

Edge Cases

Handle these before claiming the swap is complete.

Same values

No visible change

Swap is still correct.

XOR caveat

Integers only

List swap is a clean compact PHP option.

Negatives

Temp / list OK

-4 and 20 swap fine.

Zeros

Valid

0, 3 becomes 3, 0.

Strings / floats

Use temp or list

Skip XOR.

List indices

Same pattern

arr[i], arr[j] = arr[j], arr[i]

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Sorting building block. Almost every in-place sort swaps elements.
  • List evaluates RHS first. That is why [$a, $b] = [$b, $a] is safe.
  • XOR is optional trivia. Prefer readability unless asked specifically.
  • All variants are O(1). Cost does not grow with the numbers’ magnitude.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Temp swap 5, 10

  • Reproduce Example 1
  • Expect 10, 5

2. List swap

  • Use [$a, $b] = [$b, $a]
  • Same result

3. Equal values

  • Swap 7, 7
  • Confirm still 7, 7

4. List indices

  • Swap arr[0] and arr[1]
  • Use unpacking

Notes

  • Core idea: exchange values without losing either one.
  • PHP compact style: [$a, $b] = [$b, $a].
  • XOR: mainly an interview trick for integers.
  • All swap variants are constant-time and constant extra space.

Quick Takeaway: save before overwrite — or write [$a, $b] = [$b, $a].

⏱️ Time and Space Complexity

VersionTimeExtra space
Temp swapO(1)O(1)
List swapO(1)O(1)
XOR swapO(1)O(1)

Swapping two variables does a fixed number of assignments regardless of the values.

Wrap Up

🎉 Conclusion

Swapping exchanges two values without losing either one. Learn the temp-variable pattern for every language, prefer [$a, $b] = [$b, $a] or $temp in PHP, and treat XOR as optional trivia.

Practice the three examples above, then continue to triangular numbers.

Save first — or use [$a, $b] = [$b, $a].

💡 Best Practices

✅ Do

  • Save before overwrite
  • Prefer list swap or temp in PHP
  • Print before and after
  • Know the temp pattern
  • Test equal values

❌ Don’t

  • Assign a = b first alone
  • XOR floats or strings
  • Skip readability for cleverness
  • Assume equals breaks swap
  • Forget list-index unpacking exists

Key Takeaways

Knowledge Unlocked

Five things to remember about swapping

Exchange values safely — then use the idea in sorting.

5
Core concepts
, 02

List

[$a, $b] = [$b, $a]

PHP
^ 03

XOR

ints only

Trick
= 04

Equals

still correct

Edge
O 05

Cost

O(1)

Analysis

❓ Frequently Asked Questions

After swapping, the first variable stores the old value of the second, and the second stores the old value of the first.
Not always. PHP supports list destructuring: [$a, $b] = [$b, $a].
It teaches the core memory idea and works similarly across many languages.
Yes for integers, but it is less readable than temp or list swap, so it's mostly an interview trick.
Swap still works; values remain the same.
Yes. Temp and list swap work for any values; XOR is for integers only.
All common swap variants are O(1) time and O(1) extra space.
Show temp first, then mention [$a, $b] = [$b, $a] as a compact PHP style.

Did you Know? 🔊

Swapping values is one of the smallest building blocks in sorting. In PHP, [$a, $b] = [$b, $a] is a clean one-liner; the classic $temp version is still the clearest interview explanation.

Continue to Triangular Number

Learn how to check whether a number is triangular in PHP.

Triangular number tutorial →

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