PHP Program to Swap Two Numbers
In PHP, you can swap two numbers using a temporary variable like this:
$temp = $a; $a = $b; $b = $temp; which exchanges the values of $a and $b.Examples
Inputa = 5, b = 10
OutputAfter swap: a = 10, b = 5
Inputa = -3, b = 7
OutputAfter swap: a = 7, b = -3
Inputa = 0, b = 0
OutputAfter swap: a = 0, b = 0
How to Think About It
To swap two numbers, think of holding one number temporarily so you don't lose it when you overwrite its variable. Store the first number in a temporary place, assign the second number to the first variable, then put the temporary number into the second variable.
Algorithm
1
Get the first number and store it in a temporary variable.2
Assign the second number's value to the first number's variable.3
Assign the temporary variable's value to the second number's variable.4
Print or return the swapped values.Code
php
<?php $a = 5; $b = 10; // Swap using a temporary variable $temp = $a; $a = $b; $b = $temp; echo "After swap: a = $a, b = $b"; ?>
Output
After swap: a = 10, b = 5
Dry Run
Let's trace swapping a = 5 and b = 10 through the code
1
Store first number in temp
$temp = 5 (value of a)
2
Assign second number to first
$a = 10 (value of b)
3
Assign temp to second number
$b = 5 (value of temp)
| Variable | Value |
|---|---|
| $temp | 5 |
| $a | 10 |
| $b | 5 |
Why This Works
Step 1: Temporary storage
We use $temp to hold the value of $a so it is not lost when we overwrite $a.
Step 2: Overwrite first variable
We assign the value of $b to $a, so now $a has the second number.
Step 3: Restore second variable
We assign the stored value in $temp to $b, completing the swap.
Alternative Approaches
Swap without temporary variable using arithmetic
php
<?php $a = 5; $b = 10; $a = $a + $b; $b = $a - $b; $a = $a - $b; echo "After swap: a = $a, b = $b"; ?>
This method avoids extra variable but can cause overflow with very large numbers.
Swap without temporary variable using list()
php
<?php $a = 5; $b = 10; list($a, $b) = array($b, $a); echo "After swap: a = $a, b = $b"; ?>
This is a clean and readable PHP-specific way to swap values without a temp variable.
Complexity: O(1) time, O(1) space
Time Complexity
Swapping two numbers takes constant time because it involves only a fixed number of assignments.
Space Complexity
Using a temporary variable requires constant extra space, which is minimal and efficient.
Which Approach is Fastest?
All methods run in constant time; using list() is cleanest in PHP, while arithmetic swap avoids extra variables but risks overflow.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Temporary variable | O(1) | O(1) | Safe and clear swapping |
| Arithmetic swap | O(1) | O(1) | No extra variable but risk with large numbers |
| list() swap | O(1) | O(1) | Clean PHP syntax, readable |
Use a temporary variable to swap values safely and clearly in PHP.
Forgetting to use a temporary variable causes one value to be overwritten and lost.