move array pointer backwards

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

move array pointer backwards

Post by yaron »

Hello all,
I'm looping through an array with foreach.
In a specific case I want to move the array pointer backwards that the foreach will repeat this value again.
prev() doesn't do that - its just returns the previous element but the array pointer remains and therefor the foreach loop will not repeat it.
any ideas?
Nay
Forum Regular
Posts: 951
Joined: Fri Jun 20, 2003 11:03 am
Location: Brisbane, Australia

Post by Nay »

Maybe use a normal loop instead of foreach() might do...

-Nay
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

using for

Post by yaron »

I thought about using for instead of foreach but I can't move the index because the key is a string!!
Stoneguard
Forum Contributor
Posts: 101
Joined: Wed Aug 13, 2003 9:02 pm
Location: USA

Post by Stoneguard »

Is this a case where you want to be able to move forward and backward multiple times? sounds kind of dangerous (as in, it would be easy to get stuck in an infinite loop).

Buy anyway, since your indexes in the array are keys, why not make an array of the keys and then just use those with prev() and next()? Then just call your original array with the value of the current elemetn in the new array? Now you are no longer limited by the keyed index.

Also, you can check out the list() and each() functions in the documentation. http://us4.php.net/manual/en/function.each.php
evilMind
Forum Contributor
Posts: 145
Joined: Fri Sep 19, 2003 10:09 am
Location: Earth

Post by evilMind »

Code: Select all

<?php
$array = array( 'foo' => 'bar' , 'foobar' => 'barfoo' );
function foo( $theArray ) {
   $array_keys = array_keys($theArray);
   foreach ( $theArray AS $key => $value ) {
      echo "Key=> $key , Value => $value \n";
      if ( /* YourConditionIsMet */ ) {
         foo( $theArray );
      }
   }
}
foo( $array );

?>
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

you can do that with a while ( list(..) = each(..) ) loop

Code: Select all

<?php
$arr = array(1, 4, 5);

$sum = 1;
while( list(,$value)=each($arr) )
{
	echo $value, "<br />\n";
	if(	$sum < $value )
		prev($arr);
	
	$sum += $value;	
}

echo $sum;
?>
But as mentioned it's quite dangerous
Post Reply