purencool Posted August 17, 2009 Share Posted August 17, 2009 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 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 More sharing options...
thebadbad Posted August 17, 2009 Share Posted August 17, 2009 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); Link to comment https://forums.phpfreaks.com/topic/170606-solved-moving-array-element/#findComment-899861 Share on other sites More sharing options...
purencool Posted August 17, 2009 Author Share Posted August 17, 2009 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); Link to comment https://forums.phpfreaks.com/topic/170606-solved-moving-array-element/#findComment-899867 Share on other sites More sharing options...
ignace Posted August 17, 2009 Share Posted August 17, 2009 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); } } Link to comment https://forums.phpfreaks.com/topic/170606-solved-moving-array-element/#findComment-899881 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.