Jump to content

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);
    }
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.