Home  >  Article  >  Backend Development  >  How to exchange the values ​​of two variables in PHP without using the third parameter

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

青灯夜游
青灯夜游Original
2021-09-17 17:53:352304browse

Method: 1. Use "$a=$a $b;$b=$a-$b;$a=$a-$b;" to achieve exchange; 2. Use "list($ b,$a)=array($a,$b);” to exchange; 3. Use the string splitting function explode provided in PHP to implement the exchange.

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

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

No need to Three variables exchange the values ​​of two variables

Method 1:

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

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

Method 2:

<?php
$a=333;
$b=444;
list($b,$a)=array($a,$b);
echo $a."<br>";
echo $b;
?>

Output result:

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

Method 3: Let’s use PHP The provided string splitting function explode is implemented.

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

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

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to exchange the values ​​of two variables in PHP without using the third parameter. 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