Home >Backend Development >PHP Problem >How to exchange the values of two variables in PHP without using intermediate variables
Interchange method: 1. Use the string splitting function explode() provided by PHP to achieve this. The syntax "$b=explode("|",$a."|".$b);$a =$b[1];$b=$b[0];"; 2. Use assignment operations and addition and subtraction operations to achieve this. The syntax is "$a=$a $b;$b=$a-$b;$ a=$a-$b;"; 3. Use arrays and list() functions to implement, the syntax is "list($b,$a)=array($a,$b);".
The operating environment of this tutorial: windows7 system, PHP8 version, DELL G3 computer
There is no need for intermediate variables in PHP ( The third variable) exchanges the values of the two variables
Method 1: Use the string splitting function explode provided by PHP to achieve
<?php $a=333; $b=444; $b=explode("|", $a."|".$b); var_dump($b); $a=$b[1]; $b=$b[0]; echo $a."<br>"; echo $b; ?>
Output result:
Method 2: Use assignment operations and addition and subtraction operations to realize
<?php header("Content-type:text/html;charset=utf-8"); $a=333; $b=444; $a=$a+$b; $b=$a-$b; $a=$a-$b; echo $a."<br>"; echo $b; ?>
Output result:
Method 2: Use arrays and list() functions to implement
Implementation ideas:
Store the values of two variables into an array in order
Use list() to assign the values in the array to two variables in reverse order
list() function is used to assign values to a set of variables in one operation.
<?php $a=333; $b=444; list($b,$a)=array($a,$b); echo $a."<br>"; echo $b; ?>
Output results:
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to exchange the values of two variables in PHP without using intermediate variables. For more information, please follow other related articles on the PHP Chinese website!