3v4l.org

run code in 300+ PHP versions simultaneously
<?php function mkProductList($array) { // $tmpVal get product of all elements $tmpVal = 1; // Count zeros in array $cnt = count(array_keys($array, 0)); // If there are two or more zeros, then product of all elements will be zero // No make sense to do // Fill array with zeros and return it if ($cnt > 1) { $array = array_fill_keys(array_keys($array), 0); return $array; } // If there are one or no zeros, then get product of all elements, exclude zero, // cause multiply by zero equal zero foreach($array as $value) { if ($value != 0) { $tmpVal *= $value; } } // If there are one zero, then product of all elements will be zero // exclude zero position in input array, it will be product of all elements if ($cnt == 1) { $array = array_fill_keys(array_keys($array), 0); $array[array_search(0, $array)] = $tmpVal; return $array; } // If there are no zeros, then we replace velues in input array // Product of all elements we devide by current element value // Result is product of all elements, exclude current element value foreach($array as $key => $value) { $array[$key] = $tmpVal / $value; } return $array; } // tests var_dump(mkProductList(array(1,2,3,4))); var_dump(mkProductList(array())); var_dump(mkProductList(array(-0.5, 100, 20))); ?>
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
array(4) { [0]=> int(24) [1]=> int(12) [2]=> int(8) [3]=> int(6) } array(0) { } array(3) { [0]=> float(2000) [1]=> float(-10) [2]=> float(-50) }

preferences:
240.94 ms | 404 KiB | 327 Q