Home  >  Article  >  Backend Development  >  PHP中如何不引入第三个变量的条件下实现:交换两个变量的值?

PHP中如何不引入第三个变量的条件下实现:交换两个变量的值?

WBOY
WBOYOriginal
2016-06-23 13:39:54912browse

(1)一般情况下,我们只需要引入一个临时变量中转一下即可:

<?php $a=2;	$b=3;	echo "交换之前a=".$a.",b=".$b;	echo "<br />";	$tmp=$a;	$a=$b;	$b=$tmp;	echo "交换之前a=".$a.",b=".$b;?>

(2)而如果不引入临时变量时,怎么操作呢?其实本质还是需要第三者插足的,只是这个第三者我们可以自己组装,核心思想是利用已有的2个变量创造一个变量。

<?php $a=2;	$b=3;	echo "交换之前a=".$a.",b=".$b;	echo "<br />";	$a=$a+$b;	$b=$a-$b;	$a=$a-$b;	echo "交换之前a=".$a.",b=".$b;?>


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