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

Link to comment
Share on other sites

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().

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.