Home >Backend Development >PHP Tutorial >Take a look at the four methods in PHP to exchange two integer variables

Take a look at the four methods in PHP to exchange two integer variables

藏色散人
藏色散人forward
2021-11-16 14:43:403346browse

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

##This is the hardest to understand

$a = 1;
$b = 3;
$a = $a ^ $b;
$b = $a ^ $b;
$a = $a ^ $b;
var_dump($a, $b);

  • Use list structure

Note that list () is a structure similar to array ()

This is a comment Suggested by qufo users, thank you very much

When using list, please pay attention to the PHP version

$a = 4; $b = 5;
list($b, $a) = [$a, $b];//等同于 [$b, $a] = [$a, $b];
var_dump($a , $b);

Recommended study: "

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!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete