PHP swap

1 개요[ | ]

PHP swap
$a = 3; $b = 5;
list($a,$b) = [$b,$a];
echo "a=$a, b=$b";
function swap(&$a, &$b) {
	list($a,$b) = [$b,$a];
}
$a = 3;
$b = 5;
swap($a, $b);
echo "a=$a, b=$b";
swap with temp
function swap(&$a, &$b) {
	$temp = $b;
	$b = $a;
	$a = $temp;
}
$a = 3; $b = 5;
swap($a, $b);
echo "a=$a, b=$b";
xor swap
$a = 3; $b = 5;
$a ^= $b ^= $a ^= $b;
echo "a=$a, b=$b";
function xor_swap(&$a, &$b) {
    $a = $a ^ $b;
    $b = $a ^ $b;
    $a = $a ^ $b;
}
$a = 3; $b = 5;
xor_swap($a, $b);
echo "a=$a, b=$b";

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}