Calculating factorial of number in given array PHP

Program Description

This programs takes array of numbers and output factorial for each of the number in array.

Program
<?php

/*******************************************************************
 *
 * code.cheraus.com
 *
 *  A simple program for calculating factorial of all number in array in PHP.
 *
 ********************************************************************/


//input array for calculation
$input = array(1, 2, 3, 4, 5, 10);


/*
 * Approach #1
 * In this approach we are using array_map function. First parameter is name of callback function.
 * Second parameter is array whose each element is passed in callback function in parameter 1.
 *
*/
$output = array_map("factorial", $input);
print_r($output);


/*
 * Approach #2
 * We are using simple for loop and calling factorial function on each element.
 *
 */
$output = array();
foreach ($input as $key => $value) {

    $output[$key] = factorial($value);

}
print_r($output);


//recursive factorial function
function factorial($n)
{

    if ($n == 1) {
        return 1;
    }

    return $n * factorial($n - 1);

}


?>

Output

[0] => 1
[1] => 2
[2] => 6
[3] => 24
[4] => 120
[5] => 3628800

Comments
comments powered by Disqus