Home > Backend Development > PHP Problem > How to exchange the values ​​of two variables in PHP without using intermediate variables

How to exchange the values ​​of two variables in PHP without using intermediate variables

青灯夜游
Release: 2023-03-17 20:50:02
Original
3079 people have browsed it

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);".

How to exchange the values ​​of two variables in PHP without using intermediate variables

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

Output result:

How to exchange the values ​​of two variables in PHP without using intermediate variables

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

Output result:

How to exchange the values ​​of two variables in PHP without using intermediate variables

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

Output results:

How to exchange the values ​​of two variables in PHP without using intermediate variables

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!

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