Page 1 of 1
move array pointer backwards
Posted: Wed Oct 08, 2003 11:01 am
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?
Posted: Wed Oct 08, 2003 11:04 am
by Nay
Maybe use a normal loop instead of foreach() might do...
-Nay
using for
Posted: Wed Oct 08, 2003 11:08 am
by yaron
I thought about using for instead of foreach but I can't move the index because the key is a string!!
Posted: Wed Oct 08, 2003 11:17 am
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
Posted: Wed Oct 08, 2003 12:12 pm
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 );
?>
Posted: Wed Oct 08, 2003 11:07 pm
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