Course: PHP

Progress (0%)

# Exercise: Multiply All

Exercise 16 Very easy

Prerequisites for the exercise

1. PHP `for` Loop
2. All previous chapters

## Objective

Create a function to multiply all the numbers in a given array and return the product.

## Description

Consider the following array of numbers:

``````<?php

\$nums = [1, 5, 70, -2, -1, -0.5];``````

If we multiply all the numbers together, we get the value `-350`.

In this exercise, you ought to create a function `multiply_all()` that takes in an array of numbers and returns back their product.

If the array is empty, the value returned should be `NULL`.

Here are some examples of the usage of the function:

``````<?php

echo multiply_all([1, 5, 70, -2, -1, -0.5]), "\n";
echo multiply_all([2, 2, 2]), "\n";
echo multiply_all([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), "\n";
var_dump(multiply_all([]));``````
-350 8 3628800 NULL

## New file

Inside the directory you created for this course on PHP, create a new folder called Exercise-16-Multiply-All and put the .php solution files for this exercise within it.

## Solution

Let's start by defining the `multiply_all()` function:

``````<?php

function multiply_all(\$nums) {
// Code to go here.
}``````

The `\$nums` parameter represents the array passed into the function that contains the number to be multiplied together.

First up, we'll deal with the special case, i.e. when `\$nums` is empty, where we have to return `NULL`:

``````<?php

function multiply_all(\$nums) {
\$len = count(\$nums);
if (!\$len) {
return NULL;
}
}``````

Beyond the `if` shown here, it's known for sure that `\$nums` contains some numbers. Likewise, we ought to multiply them all using a `for` loop.

In this regard, we'll create a variable `\$product` to keep track of this product. Initially, it'll be equal to `1` since 1 is the multiplicative identity of numbers:

``````<?php

function multiply_all(\$nums) {
\$len = count(\$nums);
if (!\$len) {
return NULL;
}

// \$nums contains some numbers, so compute the product.
\$product = 1;
}``````

Now, let's get done with the `for` loop:

``````<?php

function multiply_all(\$nums) {
\$len = count(\$nums);
if (!\$len) {
return NULL;
}

// \$nums contains some numbers, so compute the product.
\$product = 1;
for (\$i = 0; \$i < \$len; \$i++) {
\$product *= \$nums[\$i];
}
return \$product;
}``````

And this completes the exercise.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage