Jump to content

[SOLVED] reorder an array


AV1611

Recommended Posts

I don't think there is an easy way to do this, but I wanna ask just in case:

 

I have an array keys like 0,1,2,3,4 etc....

 

I wanna display the result in this order:  1,0,2,3,4,5,6,7 etc...

In other words, I wanna swap just the first two elements.

 

My two ideas are either to do an if that stores the first then returns is with another if

or

make a counter and if of of that...

 

is there a better way? or should I just do what I already thought? I can manage the code for my ideas...

Link to comment
https://forums.phpfreaks.com/topic/43496-solved-reorder-an-array/
Share on other sites

Well, without knowing the purpose it is difficult to give a definitive answer. depending on how many times you will need to iterate through the array you could just leave them in place and adjust your iterations accordingly. However, if you really want to have the keys in a particular order, I believe you need to create the keys in that order. You could simply create a function to reorder the keys:

 

This may not be the most efficient, but it does what you ask:

 

<?php
function reorderArray($array) {
  $newArray = array();
  foreach ($array as $key => $value) {
    if ($key == 0) { $zeroVal = $value; }
    elseif ($key == 1) {
      $newArray[1] = $value;
      $newArray[0] = $zeroVal;
    } else {
      $newArray[$key] = $value;
    }
  }
  return $newArray;
}

$test = array('A','B','C','D');
$test = reorderArray($test);
print_r($test);

 

Would produce this output:

Array
(
    [1] => B
    [0] => A
    [2] => C
    [3] => D
)

 

 

EDIT: On second thought, if these are large arrays you would want to pop off the first two elements and reorder them into a new array and then push the new array onto the top of the remaining array.

I'll go with what Thorpe said.

 

By way of explanation, the array is a text string output from a remote device that I am parsing out, so I can't pull the array in a different order.  I just want to display the 2nd element prior to the first for cosmetic reasons.

 

Thanks all...

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.