交换两个变量值,而不在PHP中使用第三个变量 [英] Swap two variables value without using third variable in php
本文介绍了交换两个变量值,而不在PHP中使用第三个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想分享一个在访谈中大部分时间都被问到的问题,但我无法回答该问题,但最终我找到了答案:
I want to share 1 question which is asked most of the time in interviews and I wasn't able to e answer that question, but finally I found the answer:
如何在不使用第3个变量的情况下交换2个变量的值?
How to Swap 2 variable value without using 3rd variable??
推荐答案
此方法适用于任何变量类型:
This method will work for any variable type:
$a = 5;
$b = 6;
list($a, $b) = array($b, $a);
print $a . ',' . $b;
输出:
6,5
另一种简单方法(仅适用于数字,不适用于字符串/数组/等)是
Another simple way (which only works for numbers, not strings/arrays/etc) is
$a = $a + $b; // 5 + 6 = 11
$b = $a - $b; // 11 - 6 = 5
$a = $a - $b; // 11 - 5 = 6
print $a . ',' . $b;
输出:
6,5
这篇关于交换两个变量值,而不在PHP中使用第三个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文