Home > php教程 > php手册 > body text

PHP不要第三变量直接交换2个变量值的方法

PHPz
Release: 2018-10-20 15:19:32
Original
866 people have browsed it

以前做过一道php面试题是这样的:不使用第三个变量实现交换两个变量的值。一般都是借助第三个中间变量来实现原来两个变量的值交换,但是这道题却要求不能使用中间变量,这对于初学者来说也算是一个难题了。网上找到的几种方法总结如下:

<span //<span 字符串版本 结合使用substr,strlen两个方法实现<span $a="a"<span ;
<span $b="b"<span ;
<span echo &#39;交换前 $a:&#39;.<span $a.&#39;,$b:&#39;.<span $b.&#39;
&#39;<span ;
<span $a.=<span $b<span ;
<span $b=<span substr(<span $a,0,(<span strlen(<span $a)-<span strlen(<span $b<span )));
<span $a=<span substr(<span $a, <span strlen(<span $b<span ));
<span echo &#39;交换后$a:&#39;.<span $a.&#39;,$b:&#39;.<span $b.&#39;
&#39;<span ;
 
<span echo &#39;-----------------------
&#39;<span ;
 
<span //<span 字符串版本 使用str_replace方法实现<span $a="a"<span ;
<span $b="b"<span ;
<span echo &#39;交换前 $a:&#39;.<span $a.&#39;,$b:&#39;.<span $b.&#39;
&#39;<span ;
<span $a.=<span $b<span ;
<span $b=<span str_replace(<span $b, "", <span $a<span );
<span $a=<span str_replace(<span $b, "", <span $a<span );
<span echo &#39;交换后$a:&#39;.<span $a.&#39;,$b:&#39;.<span $b.&#39;
&#39;<span ;
 
<span echo &#39;-----------------------
&#39;<span ;
 
<span //<span 字符串版本 结合使用list方法和array实现<span $a="a"<span ;
<span $b="b"<span ;
<span echo &#39;交换前 $a:&#39;.<span $a.&#39;,$b:&#39;.<span $b.&#39;
&#39;<span ;
<span list(<span $b,<span $a)=<span array(<span $a,<span $b<span );
<span echo &#39;交换后$a:&#39;.<span $a.&#39;,$b:&#39;.<span $b.&#39;
&#39;<span ;
 
<span echo &#39;-----------------------
&#39;<span ;
 
<span //<span 字符串和数字都适用 使用异或运算<span $a=&#39;a&#39;<span ;
<span $b=&#39;b&#39;<span ;
<span echo &#39;交换前 $a:&#39;.<span $a.&#39;,$b:&#39;.<span $b.&#39;
&#39;<span ;
<span $a=<span $a^<span $b<span ;
<span $b=<span $b^<span $a<span ;
<span $a=<span $a^<span $b<span ;
<span echo &#39;交换后$a:&#39;.<span $a.&#39;,$b:&#39;.<span $b.&#39;
&#39;<span ;
 
<span echo &#39;-----------------------
&#39;<span ;
 
<span //<span 只适用于数字<span $a=3<span ;
<span $b=5<span ;
<span echo &#39;交换前 $a:&#39;.<span $a.&#39;,$b:&#39;.<span $b.&#39;
&#39;<span ;
<span $a=<span $a+<span $b<span ;
<span $b=<span $a-<span $b<span ;
<span $a=<span $a-<span $b<span ;
<span echo &#39;交换后$a:&#39;.<span $a.&#39;,$b:&#39;.<span $b.&#39;
&#39;;
Copy after login

【相关教程推荐】

1. php编程从入门到精通全套视频教程
2. php从入门到精通 
3. bootstrap教程

Related labels:
php
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template