Jump to content

[SOLVED] Incrementing backwards through an array


ninedoors

Recommended Posts

I am trying to increment backwards through an array but having some problems.  I will post the arrays that I am using to trouble shoot as these are not the arrays that I will be actually using.

 

<?

$array = array(2, 2, 5, 8, 21, 15, 16);

$len = count($array);


for($i = $len; $i <= $len; --$i)
{
$h = $array[$i];
echo $h;
prev($array);
}

reset($array);
?>

 

So what I what this to produce is an array that looks like (16, 15, 21, 8, 5, 2 , 2).  Hope someone can help.  Thanks Nick

prev() is a different way of doing things to $array[$i].  It has no effect here.

 

Just do this:

 

<?php
$array = array(2, 2, 5, 8, 21, 15, 16);
$len = count($array);
for($i = $len - 1; $i >= 0; --$i)
{
$h = $array[$i];
echo $h . ", ";
}
echo "\n";
?>

 

Note that this only works when your array is indexed by consecutive integers.  An alternative is to use array_reverse(), and foreach().

Personally I would suggest against reorganizing the original array and/or making a copy of it in reverse.

 

I'd just do:

 

$len = count($array);

$i = ($len-1);

while( $i >= 0 )

{

  echo $array[$i];

  --$i;

}

 

For some reason I don't like the way a for loop looks when you're decrementing :P

Personally I would suggest against reorganizing the original array and/or making a copy of it in reverse.

 

When dealing with huge arrays, reversing them and displaying may take a fraction more then counting and displaying, but otherwise i cant see why not using it.

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.