How can we swap two variable without using third variablen in php?
Answers
Answered by
0
This method will work for any variable type:
$a = 5; $b = 6; list($a, $b) = array($b, $a); print $a . ',' . $b;
Output:
6,5
Another simple way (which only works for numbers, not strings/arrays/etc) is
$a = $a + $b; // 5 + 6 = 11 $b = $a - $b; // 11 - 6 = 5 $a = $a - $b; // 11 - 5 = 6 print $a . ',' . $b;
Output:
6,5
$a = 5; $b = 6; list($a, $b) = array($b, $a); print $a . ',' . $b;
Output:
6,5
Another simple way (which only works for numbers, not strings/arrays/etc) is
$a = $a + $b; // 5 + 6 = 11 $b = $a - $b; // 11 - 6 = 5 $a = $a - $b; // 11 - 5 = 6 print $a . ',' . $b;
Output:
6,5
Similar questions