Skipping array element in foreach loop ...

Discussion in 'PHP' started by drgeorgep, Apr 7, 2011.

  1. #1
    In this sample code, is it possible to skip an element in the array, say, 3? If so, how?

    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value)
    {
    $value = $value * 2;
    }

    Thanks
     
    drgeorgep, Apr 7, 2011 IP
  2. Jan Novak

    Jan Novak Peon

    Messages:
    121
    Likes Received:
    5
    Best Answers:
    1
    Trophy Points:
    0
    #2
    
    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as $value)
    {
        if($value==3){
            continue;
        }
        echo $value = $value * 2 . "\n";
    }
    ?>
    
    Code (markup):
    returns:
    2
    4
    8
     
    Jan Novak, Apr 7, 2011 IP
  3. Sepehr

    Sepehr Peon

    Messages:
    568
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #3
    this is one way:

    
    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) 
    {
    	if($value!=3){
    		$value = $value * 2;
    	}
    }
    ?>
    
    PHP:
    And here's another:

    
    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) 
    {
    	$i++;
    	if($i!=3){
    		$value = $value * 2;
    	}
    }
    ?>
    
    PHP:
    There are other ways if these are not what you're looking for, but you'll have to provide more details.
     
    Sepehr, Apr 7, 2011 IP
  4. drgeorgep

    drgeorgep Active Member

    Messages:
    854
    Likes Received:
    19
    Best Answers:
    0
    Trophy Points:
    58
    #4
    Thanks to Jan and Sepehr.
     
    drgeorgep, Apr 8, 2011 IP