MagePsycho
MagePsycho

Reputation: 2004

Interchange the display order in a loop

I am trying to interchange the display order in a loop.
For example i have an array $array with values: 1,2,3,4,5 and want to display the result in the order 2,1,3,4,5. I am using the following code for the purpose and which worked for me:

<?php
$array = array(
    1,
    2,
    3,
    4,
    5,
);
$tempArray = array();
$count = 1;
foreach($array as $key => $value){
    $tempArray[$key] = $value;
    if(in_array($count, array(1, 2))){
        if($count == 2){
            echo $tempArray[1] . '<br />';
            echo $tempArray[0] . '<br />';
        }
    }else{
        echo $value . '<br />';
    }
    $count++;
}

But i would like to know if there is any effective (better) way of doing so?

EDIT:

$array = array(
    1,
    2,
    3,
    4,
    5,
);
//Either
/*$temp = $array[1];
$array[1] = $array[0];
$array[0] = $temp;*/

//OR
list($array[1], $array[0]) = array($array[0], $array[1]);

foreach($array as $key => $value){
    echo $value . '<br />';
}

Either way works fine with minimum code.
Thank you guys!

Upvotes: 0

Views: 184

Answers (1)

hakre
hakre

Reputation: 198126

To change the display order of $array that is array(1, 2, 3, 4, 5) without changing the order of the elements in $array you need to define the display order and then display based on the display order:

$array   = array(1, 2, 3, 4, 5);

$display = array_keys($array);
list($display[1], $display[0]) = array($display[0], $display[1]);

foreach ($display as $key)
{
    $value = $array[$key];
    printf("%d<br />\n", $value);
}

This works - as you wrote it already yourself in the comments - by switching the order (keys) of the first two elements(0 and 1, arrays are zero-based).

Upvotes: 1

Related Questions