Objective
Originally wanted to update PHP operation socket code, but because of the project reason is not in the mood, but over time will operate SMS Gateway, then naturally update the socket code, today is mainly how to use PHP Exchange two number.
List
First, use the PHP list data structure. On the code, and then parse the
[PHP]View PlainCopyprint?
- Function swap (&$a, &$b) {
- List ( $a, $b) = Array ($b, $a);
- }
List: Assigns the value of the array to the variable in the list, which is equivalent to assigning the value of $b to $ A and assigning a value of $ A to $b. Also, note the use of the & reference operator, which is a reference pass instead of a value pass.
XOR or operation
Three features of bitwise XOR:
- 0^1=1 0^0=0 = Therefore, 0 XOR or any number equal to any number itself
- 1^0=1 1^1=0 = Therefore, 1 xor or any number equals any number of counter
- Any number of different or yourself = put yourself 0
Well, don't say much, on the code
[PHP]View PlainCopyprint?
- Function Swap1 (&$a, &$b) {
- $a = $a ^ $b;
- $b = $a ^ $b;
- $a = $b ^ $a;
- }
Well, let's analyze why it's also possible to exchange.
$a = $a ^ $b;
$b = $a ^ $b = ($a ^ $b) ^ $b = $a ^ ($b ^ $b) = $a ^ 0, according to XOR or characteristic, 0 with any number XOR or equal to any number itself. The same can be deduced, $a = $b
Exchange values for two variables in PHP