Limiting foreach?

Discussion in 'PHP' started by feonix, Jan 30, 2009.

  1. #1
    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.
     
    feonix, Jan 30, 2009 IP
  2. hassanahmad1

    hassanahmad1 Active Member

    Messages:
    150
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #2
    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):
     
    hassanahmad1, Jan 30, 2009 IP
  3. crivion

    crivion Notable Member

    Messages:
    1,669
    Likes Received:
    45
    Best Answers:
    0
    Trophy Points:
    210
    Digital Goods:
    3
    #3
    $count = 0;

    foreach ($ranked as $key => $value) {
    $count++;
    if ($count < 20) {

    print "$count number is lower than 20";
    }
    }
     
    crivion, Jan 30, 2009 IP
  4. zat88

    zat88 Banned

    Messages:
    43
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    
    $count = 0;
    
        foreach ($ranked as $key => $value) {
            if ($count < 20) {
    
                $count++;
            } else break 2;
        }
    
    PHP:
    You can use the break statement
     
    zat88, Jan 30, 2009 IP
  5. yoavmatchulsky

    yoavmatchulsky Member

    Messages:
    57
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #5
    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:
     
    yoavmatchulsky, Jan 30, 2009 IP
  6. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #6
    Can be shortened to:

    if(++$count > $num) break;
    PHP:
     
    Danltn, Jan 30, 2009 IP