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

青灯夜游
Release: 2023-03-13 07:44:01
Original
2388 people have browsed it

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

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

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

Related labels:
source:php.cn
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