In this tutorial you will learn how to quickly and simply swap the values of 2 variables in just 1 line of code without using a third variable temporarily. This article is demonstrated in PHP although the same principle applies to other languages such as C and C++.
Most people never come across the problem of having to swap the value of 2 variables, but at some point you may encounter the need to do so quickly and efficiently.
Where some would accept using a 3rd variable to do the swapping of values, others are thinking whether it is possible to do this using a more efficient method.
The following is an example demonstrates how to swap the value of 2 variables using a 3rd temporary variable:
old_value = 1
new_value = 2
temp_value = 3
temp_value = old_value
old_value = new_value
new_value = temp_value
In PHP this would look like:
$old_value = 1;That is some code just to swap the value of 2 variables. Without going into detail on how it works, the Exclusive Or (XOR) operator can be used to simplify this task.
The above example in PHP can simply be replaced using the following:
$old_value ^= $new_value ^= $old_value ^= $new_value;If you look closely, you will even notice that a 3rd variable has not been used.
To make the task of swapping variable values even simpler, you can also create your own function for doing so:
function swap (&$x, &$y) {There you have it, swapping 2 variable's values in 1 simple line of programming.
This program tell us how to swap array value. Array swap sample : ‘one’); $y = array(‘b’ => ‘two’);
list($x,$y) = array($y,$x);
echo ‘X : ‘; print_r($x); echo ‘Y : ‘; print_r($y); ?>
Output: X : Array ( [b] => two ) Y : Array ( [a] => one )
Class swap : <?php
class a { public $name = ‘alu’; } class b { public $name = ‘begun’; }
$x = new a(); $y = new b();
list($x,$y) = array($y,$x);
echo ‘X : ‘; var_dump($x); echo ‘Y : ‘; var_dump($y); ?>
In this article I introduce you to a tutorial series titled, Some Features of C++ Entities....
C++ is a computer language I want to teach in these tutorials. C++ is a very developed language...
In C++ an array is a set of consecutive objects of the same type, in memory. We see how to crea...
A database is a set of related tables. This is part 1, division 1 of a series I have on databas...
To easy way lean java programming language with a basic concepts which will help to build basic...
In this tutorial you will learn how to quickly and simply swap the values of 2 variables in jus...