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

藏色散人
Release: 2023-04-10 19:50:01
forward
3339 people have browsed it

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);
Copy after login
  • 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);
Copy after login
  • 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);
Copy after login

  • 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);
Copy after login
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!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template