A Product Array Puzzle | Function to print product array for a given array arr [ ] of size n ; Base case ; Allocate memory for the productarray ; Initialize the product array as 1 ; In this loop , temp variable contains product of elements on left side excluding arr [ i ] ; Initialize temp to 1 for product on right side ; In this loop , temp variable contains product of elements on right side excluding arr [ i ] ; print the constructed prod array ; Driver Code
< ? php function productArray ( $ arr , $ n ) { if ( $ n == 1 ) { echo "0" ; return ; } $ i ; $ temp = 1 ; $ prod = array ( ) ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) $ prod [ $ j ] = 1 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ prod [ $ i ] = $ temp ; $ temp *= $ arr [ $ i ] ; } $ temp = 1 ; for ( $ i = $ n - 1 ; $ i >= 0 ; $ i -- ) { $ prod [ $ i ] *= $ temp ; $ temp *= $ arr [ $ i ] ; } for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ prod [ $ i ] , " ▁ " ; return ; } $ arr = array ( 10 , 3 , 5 , 6 , 2 ) ; $ n = count ( $ arr ) ; echo " The ▁ product ▁ array ▁ is ▁ : ▁ STRNEWLINE " ; productArray ( $ arr , $ n ) ; ? >