배열인 변수를 합산이나 곱셈을 해주는 연산 함수가 있습니다. 다음 곱셈 함수 array_product() 사용 예제입니다.

<?php 
 $a = array(2, "4", 6, 8);
 echo "product(a) = " . array_product($a) . "\n"; 
 // 결과: product(a) = 384 


 $a = array("2one", "4", 6, (int)"8red"); 
 echo "product(a) = " . array_product($a) . "\n"; 
 // 결과: product(a) = 384 


 $a = array("2one", "4", 6, (int)"red8"); 
 echo "product(a) = " . array_product($a) . "\n"; 
 // 결과: product(a) = 0


 echo "product(a) = " . array_product(range(1,30)) . "\n"; 
 // 결과: product(a) = 2.6525285981219E+32  
 ?>  

다음은 덧셈 연산입니다.

<?php  
 $a = array(2, "4", 6, 8); 
 echo "sum(a) = " . array_sum($a) . "\n";  
 // 결과: sum(a) = 20 


 $a = array("2one", "4", 6, (int)"8red");  
 echo "sum(a) = " . array_sum($a) . "\n";  
 // 결과: sum(a) = 20  


 $a = array("2one", "4", 6, (int)"red8");  
 echo "sum(a) = " . array_sum($a) . "\n";  
 // 결과: sum(a) = 12 


 echo "sum(a) = " . array_sum(range(1,30)) . "\n";  
 // 결과: sum(a) = 465 
  

 $b = array("a" => 1.2, "b" => 2.3,"c" => 3.4); 
 echo "sum(b) = " . array_sum($b) . "\n"; 
 // 결과: 6.9 
 ?>  

이 두 함수는 산술 연산자의 영향을 받지만, 차원이 다른 배열인 경우 무시 됩니다.

<?php  
 $a = array("2one", "4", array(6,2,1), (int)"8red");  
 echo "array_product(a) = " . array_product($a) . "\n";  
 // 결과: sum(a) = 64 


 $a = array("2one", "4", array(6,2,1), (int)"red8");  
 echo "sum(a) = " . array_sum($a) . "\n";  
 // 결과: sum(a) = 6
 ?>

차원이 서로 다른 배열인 경우 함수를 따로 만들어 사용해야 합니다.

<?php  
 function multiDimArrayAdd($arr){ 
    static $sum; 


    if(is_array($arr)){ 
        foreach($arr as $k=>$v){ 
            if(is_array($arr[$k])){ 
                multiDimArrayAdd($arr[$k]); 
            } else { 
                $sum += (int)$v; 
            } 
        } 
    } 
    return $sum; 
 }
 $a = array("2one", "4", array(6,2,1), (int)"red8"); 
 echo "sum(a) = " . multiDimArrayAdd($a) . "\n";  
 // 결과: sum(a) = 15 
 ?>

0 댓글