# PHP program to calculate factors of a given number

In this article, we are going to learn how to create a function in PHP that will help us calculate factors of any given number? By Kongnyu Carine Last updated : December 19, 2023

## Prerequisites

To understand this example, you should have the basic knowledge of the following PHP topics:

## PHP - Calculating Factors of a Number

For instance, if we have to list the factors of a number y. Then, we have to look for all possible numbers within the range 0 to the number y (with 0 exclusive because we do not divide a number by 0) that gives no remainder when it divides y.

### Example

```Input 6
Output {1,2,3,4,5,6,}.
```

Let's Write out a PHP function to do this for us:

## PHP code to calculate factors of a number

```<?php
//We Define a function that gets
//an argument and return the factors
//of the number it got.
// Function definition
function factors_of_a_number(\$n)
{
if (\$n == 0)
{
// because we cannot divide 0/0 does not exist
echo "Zero has no factors";
}
else
{
// format our answer to look good.
print_r("The factors of \$n are {");
//We will use a for loop to loop through
// each number in the series  1 to our number \$n
// dividing \$n by each number
for (\$x = 1;\$x <= \$n;\$x++)
{
// the modulus operator
// helps us get the remainder of each division
\$factor = \$n % \$x;

//we will check to see which number return a 0 as reminder
// the we echo that number because it is a factor of our number \$n.
if (\$factor == 0)
{
print_r(\$x . ",");
}
}
print_r("}");
}
}
print_r(factors_of_a_number(0) . "\n");
print_r(factors_of_a_number(50) . "\n");
?>
```

### Output

```Zero has no factors
The factors of 50 are {1,2,5,10,25,50,}
```

Student's Section
Subscribe