Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
)
*/
@wajdijurry

This comment has been minimized.

Copy link

@wajdijurry wajdijurry commented Sep 5, 2018

Good implementation √

@wajdijurry

This comment has been minimized.

Copy link

@wajdijurry wajdijurry commented Sep 14, 2018

Have a look to my gist, which gives you ability to add new item to the array or change position of existing item, after shifting items up or down depending on available positions.
https://gist.github.com/wajdijurry/a00752123134342ccc9d13a480c9f013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment