skip to Main Content

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


  1. 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;
    
    Login or Signup to reply.
  2. You can also swap the variables this way:

    list($a, $b) = array($b, $a);
    
    Login or Signup to reply.
  3. 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; 
    
    Login or Signup to reply.
  4. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search