So I have a foreach loop for an associative array, how can I limit the number of times it loops? Here is the code... $count = 0; foreach ($ranked as $key => $value) { if ($count < 20) { $count++; } } PHP: The above is what I was trying but it doesn't seem to work. I don't even really care if the loop runs more times than I want I need to limit an action within it to a certain number.
i didnt get what exactly you mean, but i think maybe you are trying to do this instead: $count = 0; foreach ($ranked as $key => $value) { if ($count < 20) { //put here what you want to do } $count++; } Code (markup):
$count = 0; foreach ($ranked as $key => $value) { $count++; if ($count < 20) { print "$count number is lower than 20"; } }
$count = 0; foreach ($ranked as $key => $value) { if ($count < 20) { $count++; } else break 2; } PHP: You can use the break statement
why break 2? you only need to break out of 1 control loop. else break; is enough. btw, if you only want a specific number of iteration, why not use a for loop? define('k_Count', 20); reset($ranked); for ($i = 0; $i < k_Count && (list($key, $value) = each($ranked)); ++$i) { yaba(); daba($do); } PHP: