Swap two variable values in PHP

藏色散人
Release: 2019-05-24 18:20:20
Original
11399 people have browsed it

PHP has two methods to implement the exchange of two variable values. The first method uses a third temporary variable. The second method is to swap the values of two variables without using the third variable.

Swap two variable values ​​in PHP

Below we will introduce to you thePHP method of exchanging two variable valuesthrough specific code examples.

First of all, everyone must know that exchanging two variables meansexchanging the values of variables. Typically this is done via data in memory.

Method 1: The easiest way to swap two variables is to use a third temporary variable

交换前的数字为:
"; echo "a =".$a." 且 b=".$b; $temp = $a; $a = $b; $b = $temp; echo "
交换后的数字为:
"; echo "a =".$a." 且 b=".$b."
";
Copy after login

Output:

交换前的数字为: a =15 且 b=27 交换后的数字为: a =27 且 b=15
Copy after login

Method Two: Swap two variable values without using the third variable

交换前: ". $a . ',' . $b; list($a, $b) = array($b, $a); echo "
交换后: ". $a . ',' . $b."
";
Copy after login

Output:

交换前: 15,27 交换后: 27,15
Copy after login

Note:

list() functionmeans assigning the values in the array to a set of variables

list ( mixed $var1 [, mixed $... ] ) : array
Copy after login

Like array(), this is not a real function, but a language structure. list() can assign values to a set of variables in a single operation.

Parameter var1 represents a variable. The return value is the specified array.

This article is an introduction to two methods of exchanging two variable values in PHP. It is simple and easy to understand. I hope it will be helpful to friends in need!

The above is the detailed content of Swap two variable values in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!