Home >Backend Development >PHP Problem >How to exchange the values ​​of two variables in php without using a third variable

How to exchange the values ​​of two variables in php without using a third variable

青灯夜游
青灯夜游Original
2021-09-30 16:25:332395browse

Method: 1. Use the statement "$a=$a^$b;$b=$b^$a;$a=$a^$b;"; 2. Use $b=explode( "|",$a."|".$b);$a=$b[1];$b=$b[0];" statement; 3. Use "list($b,$a)=array ($a,$b);".

How to exchange the values ​​of two variables in php without using a third variable

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php does not use a third variable to exchange the values ​​of two variables

Method 1: Use XOR operation

<?php
header("Content-type:text/html;charset=utf-8");
$a=125;
$b=854;
echo &#39;交换前 :<br />&#39;;
echo $a."<br>";
echo $b."<br>";

$a=$a^$b;
$b=$b^$a;
$a=$a^$b;
echo &#39;<br>交换后 :<br />&#39;;
echo $a."<br>";
echo $b;
?>

Output result:

How to exchange the values ​​of two variables in php without using a third variable

##Method 2:

<?php
header("Content-type:text/html;charset=utf-8");
$a=12;
$b=85;
echo &#39;交换前 :<br />&#39;;
echo $a."<br>";
echo $b."<br>";

$b=explode("|", $a."|".$b);
$a=$b[1];
$b=$b[0];
echo &#39;<br>交换后 :<br />&#39;;
echo $a."<br>";
echo $b;
?>

Output result:

How to exchange the values ​​of two variables in php without using a third variable

Method 3:

<?php
header("Content-type:text/html;charset=utf-8");
$a=126;
$b=85;
echo &#39;交换前 :<br />&#39;;
echo $a."<br>";
echo $b."<br>";

list($b,$a)=array($a,$b);
echo &#39;<br>交换后 :<br />&#39;;
echo $a."<br>";
echo $b;
?>

Output result:

How to exchange the values ​​of two variables in php without using a third variable

Recommended learning: "

PHP Video tutorial

The above is the detailed content of How to exchange the values ​​of two variables in php without using a third variable. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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