以前做过一道php面试题是这样的:不使用第三个变量实现交换两个变量的值。一般都是借助第三个中间变量来实现原来两个变量的值交换,但是这道题却要求不能使用中间变量,这对于初学者来说也算是一个难题了。网上找到的几种方法总结如下:
<span //</span><span 字符串版本 结合使用substr,strlen两个方法实现</span> <span $a</span>="a"<span ; </span><span $b</span>="b"<span ; </span><span echo</span> '交换前 $a:'.<span $a</span>.',$b:'.<span $b</span>.'<br />'<span ; </span><span $a</span>.=<span $b</span><span ; </span><span $b</span>=<span substr</span>(<span $a</span>,0,(<span strlen</span>(<span $a</span>)-<span strlen</span>(<span $b</span><span ))); </span><span $a</span>=<span substr</span>(<span $a</span>, <span strlen</span>(<span $b</span><span )); </span><span echo</span> '交换后$a:'.<span $a</span>.',$b:'.<span $b</span>.'<br />'<span ; </span><span echo</span> '-----------------------<br/>'<span ; </span><span //</span><span 字符串版本 使用str_replace方法实现</span> <span $a</span>="a"<span ; </span><span $b</span>="b"<span ; </span><span echo</span> '交换前 $a:'.<span $a</span>.',$b:'.<span $b</span>.'<br />'<span ; </span><span $a</span>.=<span $b</span><span ; </span><span $b</span>=<span str_replace</span>(<span $b</span>, "", <span $a</span><span ); </span><span $a</span>=<span str_replace</span>(<span $b</span>, "", <span $a</span><span ); </span><span echo</span> '交换后$a:'.<span $a</span>.',$b:'.<span $b</span>.'<br />'<span ; </span><span echo</span> '-----------------------<br/>'<span ; </span><span //</span><span 字符串版本 结合使用list方法和array实现</span> <span $a</span>="a"<span ; </span><span $b</span>="b"<span ; </span><span echo</span> '交换前 $a:'.<span $a</span>.',$b:'.<span $b</span>.'<br />'<span ; </span><span list</span>(<span $b</span>,<span $a</span>)=<span array</span>(<span $a</span>,<span $b</span><span ); </span><span echo</span> '交换后$a:'.<span $a</span>.',$b:'.<span $b</span>.'<br />'<span ; </span><span echo</span> '-----------------------<br/>'<span ; </span><span //</span><span 字符串和数字都适用 使用异或运算</span> <span $a</span>='a'<span ; </span><span $b</span>='b'<span ; </span><span echo</span> '交换前 $a:'.<span $a</span>.',$b:'.<span $b</span>.'<br />'<span ; </span><span $a</span>=<span $a</span>^<span $b</span><span ; </span><span $b</span>=<span $b</span>^<span $a</span><span ; </span><span $a</span>=<span $a</span>^<span $b</span><span ; </span><span echo</span> '交换后$a:'.<span $a</span>.',$b:'.<span $b</span>.'<br />'<span ; </span><span echo</span> '-----------------------<br/>'<span ; </span><span //</span><span 只适用于数字</span> <span $a</span>=3<span ; </span><span $b</span>=5<span ; </span><span echo</span> '交换前 $a:'.<span $a</span>.',$b:'.<span $b</span>.'<br />'<span ; </span><span $a</span>=<span $a</span>+<span $b</span><span ; </span><span $b</span>=<span $a</span>-<span $b</span><span ; </span><span $a</span>=<span $a</span>-<span $b</span><span ; </span><span echo</span> '交换后$a:'.<span $a</span>.',$b:'.<span $b</span>.'<br />';