臨時變數法
echo "
---臨時變數法---
";
$num1 = 3;
$num2 = 6;
echo "交換前:
", `$num1 = `, $num1, "
", `$num2 = `, $num2, "
";
$tmp = $num1;
$num1 = $num2;
$num2 = $tmp;
echo "交換後:
", `$num1 = `, $num1, "
", `$num2 = `, $num2, "
";
/*
---臨時變數法---
交換前:
$num1 = 3
$num2 = 6
交換後:
$num1 = 6
$num2 = 3
*/
加減法
echo "
---加減法---
";
$num1 = 3;
$num2 = 6;
echo "交換前:
", `$num1 = `, $num1, "
", `$num2 = `, $num2, "
";
$num1 = $num1 + $num2;
$num2 = $num1 - $num2;
$num1 = $num1 - $num2;
echo "交換後:
", `$num1 = `, $num1, "
", `$num2 = `, $num2, "
";
/*
---加減法---
交換前:
$num1 = 3
$num2 = 6
交換後:
$num1 = 6
$num2 = 3
*/
異或法
echo "
---異或法---
";
$num1 = 3;
$num2 = 6;
echo "交換前:
", `$num1 = `, $num1, "
", `$num2 = `, $num2, "
";
$num1 = $num1 ^ $num2;
$num2 = $num1 ^ $num2;
$num1 = $num1 ^ $num2;
echo "交換後:
", `$num1 = `, $num1, "
", `$num2 = `, $num2, "
";
/*
---異或法---
交換前:
$num1 = 3
$num2 = 6
交換後:
$num1 = 6
$num2 = 3
*/