To swap two numbers means exchange their values: after the swap, the first variable holds what the second had, and the second holds what the first had.
Remember
Before: a = 5, b = 10
After: a = 10, b = 5
Interview default:
temp = a
a = b
b = temp
Method
Idea
Notes
Temp variable
Save, overwrite, restore
Clearest interview answer
Arithmetic
Add / subtract without named temp
Watch large-sum edge cases
XOR
Three ^= steps
Integers only; interview trick
Approach
How to Swap Two Numbers in PHP
Four clear steps for the temp method — then optional no-temp variants.
Store the first value in $temp.
Copy the second value into the first variable.
Copy $temp into the second variable.
Or, if asked, show arithmetic / XOR as alternatives (mention readability).
Method
Idea
Time
Best for
Temp variable
$temp = $a; $a = $b; $b = $temp;
O(1)
Interviews, default answer
Arithmetic
Add then subtract twice
O(1)
No-temp follow-up
XOR
$a ^= $b three times
O(1)
Integer bit trick
Pseudocode
Pseudocode
function SwapTemp(a, b):
temp = a
a = b
b = temp
return a, b
function SwapArithmetic(a, b):
a = a + b
b = a - b
a = a - b
return a, b
function SwapXor(a, b):
if a != b:
a = a XOR b
b = b XOR a
a = a XOR b
return a, b
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Default
Use a temporary variable
Temp steps
$temp = $a; $a = $b; $b = $temp;
list() form
[$a, $b] = [$b, $a]; (PHP 7.1+)
Equal values
Swap still works; result unchanged
XOR
Integers only; optional trick
Classic check
5, 10 → 10, 5
Try it
Live Preview
Enter two integers and swap them with the temporary-variable method.
Whole numbers only. Tap a chip or type a pair.
Result
Before: a = 5, b = 10
temp = 5
a = 10
b = 5
After: a = 10, b = 5
Trace
Worked Walkthrough — a = 5, b = 10
Trace the temporary-variable swap step by step.
Calculation
Start: a = 5, b = 10
Step 1: temp = a → temp = 5
Step 2: a = b → a = 10
Step 3: b = temp → b = 5
Result: a = 10, b = 5
Code
PHP Programs
Start with a temporary variable — the interview default. Then show arithmetic and XOR as no-temp alternatives.
Example 1 — Swap Using Temp Variable
Save the first value, overwrite it, then restore into the second variable.