Jump to content

[SOLVED] moving array element


purencool

Recommended Posts

I have an array that has a element in four that I want to move to the top of the array

my problem is I keep loosing data.

 

In the code below preg_grep searchs the array and in this case come back with key at four. All I want it to do now in move number four to position 0 and everything else move down one position but I can get it to work!!!!!!1 :facewall: My logic is right( I think) but the code isn't.


           $placement = preg_grep("/Home/",$menuArray);
           print_r($placement);
          array_shift($menuArray,$placement);

Link to comment
https://forums.phpfreaks.com/topic/170606-solved-moving-array-element/
Share on other sites

You can use a combination of array_unshift() and array_pop():

 

array_unshift($placement, array_pop($placement));

Edit: I assumed you wanted to move the last element to the top of the array. If it should be the element at index 4, you can do this instead:

 

$temp = $placement[4];
unset($placement[4]);
array_unshift($placement, $temp);

This code was kinda close I made small changes and it worked. But It has shown large flaw in my logic.

 

This is what the code that work looks like

           $placement = preg_grep("/Home/",$menuArray);
            unset($menuArray[4]);
            array_unshift($menuArray, $placement[4]);

 

This is what i would like it to look like. I thought that preg_grep returns a key number but it doesn't it returns an array.

           $placement = preg_grep("/Home/",$menuArray);
            unset($menuArray[$placement]);
            array_unshift($menuArray, $placement);

You can use a combination of array_unshift() and array_pop():

 

array_unshift($placement, array_pop($placement));

Edit: I assumed you wanted to move the last element to the top of the array. If it should be the element at index 4, you can do this instead:

 

$temp = $placement[4];
unset($placement[4]);
array_unshift($placement, $temp);

 

If you want every fourth element to move to the first place, use:

 

$sizeof = sizeof($menuArray);
for ($i = 1; $i <= $sizeof; ++$i) {
    if (0 === ($i % 4)) {
        $temp = $menuArray[$i];
        unset($menuArray[$i]);
        array_unshift($menuArray, $temp);
    }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.