Home >Backend Development >PHP Tutorial >How to exchange the values of two variables in php
php method to exchange the values of two variables: 1. Use a third variable to exchange two numbers, code such as "echo ."a =".$a." and b=".$b. "\n";"; 2. Exchange two variable values without using the third variable, code such as "list($a, $b)=array...".
The operating environment of this article: Windows 7 system, Dell G3 computer, PHP version 7.1.
This article mainly introduces to you the specific implementation method of PHP exchanging the values of two variables.
Exchanging two variables means exchanging the values of the variables with each other. Typically this is done via data in memory.
There are two ways to exchange two variables:
Below we will introduce the method of exchanging the values of two variables in PHP through specific code examples.
Method 1: Use the third variable to exchange two numbers
The code is as follows:
<?php $a = 15; $b = 27; echo "交换前的数字是:"."a =".$a." and b=".$b; $temp = $a; $a = $b; $b = $temp; echo "<br>交换后的数字是:"."a =".$a." and b=".$b."\n";
The effect is as follows:
Method 2: Exchange two variable values without using the third variable
The code is as follows:
<?php $a = 15; $b = 276; echo "交换前:"."a=". $a . ',' ."b=". $b; list($a, $b) = array($b, $a); echo "<br>交换后:"."a=". $a . ',' ."b=". $b;
list() means assigning the values in the array to a set of variables.
Note: In versions prior to PHP 7.1.0, list() can only be used for numerically indexed arrays, and it is assumed that numerical indexing starts from 0.
In PHP 5, list() starts assigning values from the rightmost parameter; in PHP 7, list() starts assigning values from the leftmost parameter.
The output result is as shown below:
Recommended learning tutorial: "PHP Tutorial"
This article is about the specific method of PHP exchanging the values of two variables. I hope it will be helpful to friends in need!
The above is the detailed content of How to exchange the values of two variables in php. For more information, please follow other related articles on the PHP Chinese website!