Is There a PHP Function for Swapping the Values of Two Variables

Is there a PHP function for swapping the values of two variables?

TL;DR

There isn't a built-in function. Use swap3() as mentioned below.

Summary

As many mentioned, there are multiple ways to do this, most noticable are these 4 methods:

function swap1(&$x, &$y) {
// Warning: works correctly with numbers ONLY!
$x ^= $y ^= $x ^= $y;
}
function swap2(&$x, &$y) {
list($x,$y) = array($y, $x);
}
function swap3(&$x, &$y) {
$tmp=$x;
$x=$y;
$y=$tmp;
}
function swap4(&$x, &$y) {
extract(array('x' => $y, 'y' => $x));
}

I tested the 4 methods under a for-loop of 1000 iterations, to find the fastest of them:

  • swap1() = scored approximate average of 0.19 seconds.
  • swap2() = scored approximate average of 0.42 seconds.
  • swap3() = scored approximate average of 0.16 seconds. Winner!
  • swap4() = scored approximate average of 0.73 seconds.

And for readability, I find swap3() is better than the other functions.

Note

  • swap2() and swap4() are always slower than the other ones because of the function call.
  • swap1() and swap3() both performance speed are very similar, but most of the time swap3() is slightly faster.
  • Warning: swap1() works only with numbers!

Swap two variables value without using third variable in php

This method will work for any variable type:

$a = 5;
$b = 6;
list($a, $b) = array($b, $a);
print $a . ',' . $b;

Output:

6,5

Another simple way (which only works for numbers, not strings/arrays/etc) is

$a =  $a + $b;  // 5 + 6 = 11
$b = $a - $b; // 11 - 6 = 5
$a = $a - $b; // 11 - 5 = 6
print $a . ',' . $b;

Output:

6,5

Make a substitution between the values of two variables in PHP

Try this :

$a = "Cat";
$b = "Dog";

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

echo $a;
echo $b;

Swap array values with php

Try this:

$a = array(
0 => 'contact',
1 => 'home',
2 => 'projects'
);
$temp = $a[0];
$a[0] = $a[1];
$a[1] = $temp;

How does the XOR trick to swap two variables really work on a string?

PHP applies bitwise operators to strings by applying it to each character individually.

PHP: Bitwise Operators:

Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.

This will work if both strings have the same number of characters, or more precisely the same number of bytes. If the above quote is really precise, then it may only work for ASCII-only strings.

Swapping two numbers using only two variables

The swap is performed using XOR, which is typically written as a plus within a circle; for example:

a := 5
b := 7

a := a xor b (2)
b := a xor b (5)
a := b xor a (7)

Swap elements with php between two html files

A part of the functionality. The purpose of this is for a teacher to update her schedule. She enters this page to make the changes and those changes reflect in the main page for her potential students to see

This is pretty simple... basically you just need to ouptut the data, and use slightly different markup. So the first thing you need to do split the container and the content and then rename files so you might have:

In scheduleAdmin.php:

<?php include(__DIR__ . '/functions.php'); // include path/to/this/files/folder/functions.php ?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<!-- your html -->
<?php // use the special include function to include the partial for the table ?>
<?php include_partial('_scheduleTable.php', array('mode' => 'admin')); ?>
<!-- the rest of your html -->
</body>
</html>

And then in schedule.php:

<?php include(__DIR__ . '/functions.php'); // include /path/to/this/files/folder/functions.php ?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<!-- your html -->
<?php // use the special include function to include the partial for the table ?>
<?php include_partial('_scheduleTable.php', array('mode' => 'admin')); ?>
<!-- the rest of your html -->
</body>
</html>

Now we need to create the include_partial function, which will take the name of a 'partial' (an html fragment) and an array of named variables to be available in that 'partial':

// functions.php

/**
* Directly renders a partial to the screen
*
* @param string $file the filesystem path to the partial
* @param array $vars variables that should be available to the partial
*/
function include_partial($file, $vars = array()) {
// let get_partial do all the work - this is just a shortcut to
// render it immediately
echo get_partial($file, $vars);
}

/**
* Get the contents of a partial as a string
*
* @param string $file the filesystem path to the partial
* @param array $vars variables that should be available to the partial
* @return string
*/
function get_partial($file, $vars = array()) {
// open a buffer
ob_start();

// import the array items to local variables
// ie 'someKey => 'someValue' in the array can be accessed as $someKey
extract($vars);

// include the partial file
include($file);

// get the contents of the buffer and clean it out
// then return that
return ob_get_clean();
}

So now that we have that set we just need to create out partial file _scheduleTable.php:

<?php $classnname = isset($mode) && $mode == 'admin' ? 'the_css_class_for_admin' : 'the_other_css_class'; ?>
<table id="schedule">
<tr class="<?php echo $classname ?>" >
<!-- your td's and what not - jsut needed something to show you how to echo the classname -->
</tr>
</table>

Swap two key/value pairs in an array

I thought there would be really simple answer by now, so I'll throw mine in the pile:

// Make sure the array pointer is at the beginning (just in case)
reset($array);

// Move the first element to the end, preserving the key
$array[key($array)] = array_shift($array);

// Go to the end
end($array);

// Go back one and get the key/value
$v = prev($array);
$k = key($array);

// Move the key/value to the first position (overwrites the existing index)
$array = array($k => $v) + $array;

This is swapping the first and last elements of the array, preserving keys. I thought you wanted array_flip() originally, so hopefully I've understood correctly.

Demo: http://codepad.org/eTok9WA6



Related Topics



Leave a reply



Submit