Home  >  Article  >  Backend Development  >  PHP does not use the third variable

PHP does not use the third variable

藏色散人
藏色散人Original
2019-10-18 09:27:173108browse

PHP does not use the third variable

How to exchange the values ​​of two variables in PHP without using a third variable.

substr() && strlen()

Code:

<?php
/**
 * 双方变量为字符串时,可用交换方法一
 * 使用substr()结合strlen()两个方法达到交换变量值得目的
 */
$a = "This is A"; // a变量原始值
$b = "This is B"; // b变量原始值
echo &#39;交换之前 $a 的值:&#39;.$a.&#39;, $b 的值:&#39;.$b,&#39;<br>&#39;; // 输出原始值
$a .= $b; // 将$b的值追加到$a中
/**
 * $b得到$a值详解:
 *  先通过strlen()分别计算出$a和$b中字符串的长度【此时$a是原始$a和$b的合值】
 *  通过strlen($a)-strlen($b)即可得出原始$a的值长度
 *  在通过substr()方法在合并后的$a中从0开始截取到$a的长度,那么即可得到原始$a的值
 * $a得到$b值详解:
 *  由于此刻$b已经是$a的原始值了,而$a合并后的值为原始$a+原始$b的值,故用substr()在$a中从$b(原始$a)长度位置截取,则去的内容则为原始$b,则将$b值付给$a成功
 */
$b = substr($a,0,(strlen($a)-strlen($b)));
$a = substr($a, strlen($b));
echo &#39;交换之后 $a 的值:&#39;.$a.&#39;, $b 的值:&#39;.$b,&#39;<br>&#39;; // 输出结果值

Run result:

交换之前 $a 的值:This is A, $b 的值:This is B
交换之后 $a 的值:This is B, $b 的值:This is A

More PHP related knowledge, Please visit PHP Chinese website!

The above is the detailed content of PHP does not use the third variable. For more information, please follow other related articles on the PHP Chinese website!

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