Home  >  Article  >  Backend Development  >  How to exchange the values ​​of two variables in php

How to exchange the values ​​of two variables in php

藏色散人
藏色散人Original
2018-11-20 11:17:0515362browse

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

How to exchange the values ​​of two variables in php

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:

How to exchange the values ​​of two variables in php

Method 2: Exchange two variable values ​​without using the third variable

The code is as follows:

<?php
$a = 15;
$b = 276;
echo "交换前:"."a=". $a . &#39;,&#39; ."b=". $b;
list($a, $b) = array($b, $a);
echo "<br>交换后:"."a=". $a . &#39;,&#39; ."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:

How to exchange the values ​​of two variables in php

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!

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