How to replace each element in array with the product of every other elements in PHP

1 Answer

0 votes
function product_of_every_other_elements(&$arr) {
    $size = count($arr);
    
    if ($size == 0) {
        return;
    }
    
    $left = array_fill(0, $size, 0);
    $right = array_fill(0, $size, 0);
    
    $left[0] = 1;
    for ($i = 1; $i < $size; $i++) {
        $left[$i] = $arr[$i - 1] * $left[$i - 1];
    }
    
    $right[$size - 1] = 1;
    for ($j = $size - 2; $j >= 0; $j--) {
        $right[$j] = $arr[$j + 1] * $right[$j + 1];
    }
    
    for ($i = 0; $i < $size; $i++) {
        $arr[$i] = $left[$i] * $right[$i];
    }
}

$array = array(1, 2, 3, 4, 5);
        
product_of_every_other_elements($array);

print_r($array);
  
 
 
 
 
/*
run:
 
Array
(
    [0] => 120
    [1] => 60
    [2] => 40
    [3] => 30
    [4] => 24
)

*/

 



answered Sep 22, 2023 by avibootz
...