Let’s see what four methods PHP has to exchange two integer variables?
Exchange two integer variables
Use an intermediate variable
This is the easiest to understand
$a = 1; $b = 2; $temp = $a; $a = $b; $b = $temp; var_dump($a, $b);
Do not use intermediate variables, just rely on several additions and subtractions to cleverly convert
$a = 10; $b = 5; $a = $a + $b; $b = $a - $b; $a = $a - $b; var_dump($a, $b);
Use multiple XORs in bit operations
$a = 1; $b = 3; $a = $a ^ $b; $b = $a ^ $b; $a = $a ^ $b; var_dump($a, $b);
Use list structure
$a = 4; $b = 5; list($b, $a) = [$a, $b];//等同于 [$b, $a] = [$a, $b]; var_dump($a , $b);
PHP Video Tutorial"
The above is the detailed content of Take a look at the four methods in PHP to exchange two integer variables. For more information, please follow other related articles on the PHP Chinese website!