Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving up/down an item in the array by its value

Tags:

arrays

php

I cannot find an effective solution on rearranging/swapping an array item by its value by shifting by - 1 or + 1. I'm making an order on tables, if the user wants to shift the order by moving the value upwards or downwards, the array should swap the value of the desired item upwards or downwards, for example:

If the user wants to move the item order upwards:

$desired_item_to_move = 'banana';

$default_order = array('orange', 'apple', 'banana', 'pineapple', 'strawberry');

// Typically it should return this:

array('orange', 'banana', 'apple', 'pineapple', 'strawberry');

As you can see that banana and apple has been swapped, due to banana is moved upwards, if the user wants to move it down, it should swap pineapple to banana (from the first array) and so on.

I looked around on functions, array_replace was closest, but it only replaces arrays.

like image 475
MacMac Avatar asked Feb 09 '12 14:02

MacMac


People also ask

How do you move an object to the beginning of an array?

📚 The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

How do you move an element from an array to the left?

The array can be left rotated by shifting its elements to a position prior to them which can be accomplished by looping through the array and perform the operation arr[j] = arr[j+1]. The first element of the array will be added to the last of rotated array.


1 Answers

Shifting up (assuming you've checked that the item is not already the first one):

$item = $array[ $index ];
$array[ $index ] = $array[ $index - 1 ];
$array[ $index - 1 ] = $item;

Shifting down:

$item = $array[ $index ];
$array[ $index ] = $array[ $index + 1 ];
$array[ $index + 1 ] = $item;
like image 122
JJJ Avatar answered Oct 01 '22 04:10

JJJ