5

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) 
2
  • Sorry for being so vague, but what if this array will range from 2 fruits to 10 fruits in size, and I want to rearrange this array from a random index. So say the array has 6 values, and i want to rearrange starting at the 3rd index or 4th index or a random index. Commented Apr 10, 2013 at 21:13
  • I edited my answer to include a function. Commented Apr 10, 2013 at 21:15

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.