iterate array

Discussion in 'PHP' started by bumbar, Oct 11, 2012.

  1. #1
    Hello!

    I want to get the product of all elements in the array except $number

    Ihave this simple code.

    
    $arr = array(2,5,8,3);
    
    $size_arr = count($arr);
    
    $number = 3;
    
    for((int) $i=0; $i<$size_arr; $i++){
    
    	if($arr[$i] != $number) 
    	{
    		$new_arr[] = $arr[$i];
    		$multiply *= $arr[$i];
    	} 
    
    }
    
    echo $multiply; //Notice: Undefined variable: multiply in ...
    
    echo "<br>";
    
    print_r ($new_arr); //Array ( [0] => 2 [1] => 5 [2] => 8 )
    
    PHP:
    Thanx!
     
    bumbar, Oct 11, 2012 IP
  2. plussy

    plussy Peon

    Messages:
    152
    Likes Received:
    5
    Best Answers:
    9
    Trophy Points:
    0
    #2
    how I would do it?

    
    
    $arr = array(2,5,8,3);
    $number = 3;
    $new_arr = array();$multiply = 0;
    foreach ($arr as $val) {
        if($val != $number) {        array_push($new_arr,$val);        if ($multiply==0) {		$multiply = $val;	}	else {		$multiply *= $val;	}            } 
    }
    echo $multiply; //Notice: Undefined variable: multiply in ...
    echo "<br>";
    print_r ($new_arr); //Array ( [0] => 2 [1] => 5 [2] => 8 )
    
    PHP:
     
    plussy, Oct 12, 2012 IP
  3. bumbar

    bumbar Active Member

    Messages:
    68
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    91
    #3
    exellent. good job! :eek:
     
    bumbar, Oct 12, 2012 IP
  4. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #4
    You can use existing functionality:

    
    $new_array = $array= array(2,5,8,3);
    $number = 3;
    
    $key = array_search($number, $new_array);
    if ($key !== false) { unset($new_array[$key]); }
    
    echo array_product($new_array);
    echo '<br />';
    print_r($new_array);
    
    
    PHP:
     
    ThePHPMaster, Oct 15, 2012 IP