Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Rearrange array by specific index

For example I have the following code:

$sample = array(apple, orange, banana, grape);

I want to rearrange this array, by making $sample[2] the new $sample[0], while keeping the same order throughout the array.

Output should be:

Array ( [0] => banana [1] => grape [2] => apple [3] => orange) 
like image 295
anizzzz Avatar asked Oct 04 '22 10:10

anizzzz


1 Answers

Use array_shift() as many times as you need...

$sample = array('apple', 'orange', 'banana', 'grape');

$fruit = array_shift($sample);
$sample[] = $fruit;
// now $sample will be array('orange', 'banana', 'grape', 'apple');

So say you want to make a function:

function rearrange_array($array, $key) {
    while ($key > 0) {
        $temp = array_shift($array);
        $array[] = $temp;
        $key--;
    }
    return $array;
}

Now, using rearrange_array($sample, 2) you can rearrange the sample array to your desired output.

like image 152
Marty McVry Avatar answered Oct 12 '22 23:10

Marty McVry