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?
move array pointer backwards
Moderator: General Moderators
-
Stoneguard
- Forum Contributor
- Posts: 101
- Joined: Wed Aug 13, 2003 9:02 pm
- Location: USA
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
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
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 );
?>you can do that with a while ( list(..) = each(..) ) loop
But as mentioned it's quite dangerous
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;
?>