Tuesday 3 January 2017

Swap two variables value without using third variable in php

<?php
$a=5;
$b=6;

 // This method will work only for numbers:
$a =  $a + $b;  // 5 + 6 = 11
$b = $a - $b;   // 11 - 6 = 5
$a = $a - $b;  // 11 - 5 = 6
echo $a . ',' . $b;

 // This method will work for any variable type:

$a = 5;
$b = 6;
list($a, $b) = array($b, $a);
echo $a . ',' . $b;
?>

No comments:

Post a Comment