Home > Software design >  I'm trying to swap two number using operator but not able to swap the number please help to sol
I'm trying to swap two number using operator but not able to swap the number please help to sol

Time:11-29

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?

CodePudding user response:

Please replace your code

// Swapping Logic  

   $a=$a $b;  
   $b=$a-$b;  
   $a=$a $b; 

with

    $a=$a $b;  
    $b=$a-$b;  
    $a=$a-$b;

CodePudding user response:

You can also swap the variables this way:

list($a, $b) = array($b, $a);

CodePudding user response:

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.

   $a=$a $b; 
   $b=$a-$b;  
   $a=$a-$b;



// Swapping Logic  
$third = $a;  
$a = $b;  
$b = $third; 

CodePudding user response:

You can dereference in arrays in one line:

<?php
$a = 1;
$b = 2;

[$b,$a] = [$a,$b];

echo $a,' ', $b;    // 2 1

Works as far back as PHP 7.1.0

Demo: https://3v4l.org/q62Zf#v7.1.0

  •  Tags:  
  • php
  • Related