Here, I’m trying to swap the number using PHP but not able to swap.
How to solve that problem.
My Code :
<?php
$a = 45;
$b = 78;
echo "Before swapping:<br><br>";
echo "a =".$a." b=".$b;
echo "<br/><br/>";
// Swapping Logic
$a=$a+$b;
$b=$a-$b;
$a=$a+$b;
echo "After swapping:<br><br>";
echo "a =".$a." b=".$b;
?>
I’m a beginner in php just learning about logic but getting exception so any body can help how to solve it?
4
Answers
Please replace your code
with
You can also swap the variables this way:
You can just minus it with the one u added or you can try creating another variable to temporarily store the other value while you swap. storing it on a temporary variable is how people usually do it as if you have done leet code , the bubble sort is a good practice for this kind of logic.
You can dereference in arrays in one line:
Works as far back as PHP 7.1.0
Demo: https://3v4l.org/q62Zf#v7.1.0