Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move an element to first position in an array [duplicate]

Tags:

arrays

php

here is my array:

Array
(
    [0] => Array
        (
            [id] => 8
            [title] => MUSIC
        )

    [1] => Array
        (
            [id] => 17
            [title] => Indie
        )

    [2] => Array
        (
            [id] => 14
            [title] => SPORTS
        )

    [3] => Array         // Need to move this on first position
        (
            [id] => 15
            [title] => Hipster  
        )

    [4] => Array
        (
            [id] => 16
            [title] => Web Seriesdf
        )
   )

I want array with key [3] to be on first position and then the rest of the elements. I tried array_merge and array_unshift. But not working

like image 383
Aashi Avatar asked Dec 22 '25 19:12

Aashi


1 Answers

You just need to take only three steps.

- Copy n'th array in variable.
- Delete n'th index from array. using unset()
- Put variable at the 0th index of the array. Using array_unshift()

Step 1:

$array=$mainArray[N];

Step 2:

unset($mainArray[N]);

Step 3:

array_unshift($mainArray, $array);
like image 121
Alok Patel Avatar answered Dec 24 '25 09:12

Alok Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!