Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save PYovchevski/b944d9e596b3acb9d02e03229f36569a to your computer and use it in GitHub Desktop.
Save PYovchevski/b944d9e596b3acb9d02e03229f36569a to your computer and use it in GitHub Desktop.
Reorder a PHP array, moving items up or down
<?php
/*
A quick set of functions to move items in a non-associative array
up or down by one, shifting the items around it appropriately.
Original usage was to for a set of UP and DOWN buttons to
manipulate the order of an array of items stored in Wordpress option.
*/
$a = array('a','b','c','d','e');
function down($a,$x) {
if( count($a)-1 > $x ) {
$b = array_slice($a,0,$x,true);
$b[] = $a[$x+1];
$b[] = $a[$x];
$b += array_slice($a,$x+2,count($a),true);
return($b);
} else { return $a; }
}
function up($a,$x) {
if( $x > 0 and $x < count($a) ) {
$b = array_slice($a,0,($x-1),true);
$b[] = $a[$x];
$b[] = $a[$x-1];
$b += array_slice($a,($x+1),count($a),true);
return($b);
} else { return $a; }
}
// Start
print_r($a);
/* Output
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
*/
// Move item 4 up
print_r(up($a,4));
/* Output
Array
(
[0] => a
[1] => b
[2] => c
[3] => e
[4] => d
)
*/
// Move item 0 down
print_r(down($a,0));
/* Output
Array
(
[0] => b
[1] => a
[2] => c
[3] => d
[4] => e
)
*/
// Test, move the bottom item down (ie. do nothing)
print_r(down($a,4));
/* Output
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
*/
// Test, move the top item up (ie. do nothing)
print_r(up($a,0));
/* Output
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment