PHP Basics – Multiply two numbers

Multiplying two numbers is a trivial task in most programming languages. We’ll have a look at a few approaches using PHP.

Basic

At a basic level, we will use the * operator to multiply two numbers. For example 2×2 will be written as:

2 * 2

Let’s assign that to a variable named integer like so:

$integer = 2 * 2;

Let’s use the echo statement to output the results. Here’s what the full code looks like.

<?php
    $integer = 2*2;
	echo $integer;

Creating a simple function

In this section, we’ll create a simple function called multiply. Our function that takes two parameters. We’ll use variables $a and $b to pass in our arguments.

function multiply($a,$b) {}

In the body of our multiply function, we will use the return statement to output the product of the numbers passed in.

return $a * $b;

Here’s what our function looks like

function multiply($a,$b) {
  return $a * $b; 
}

We can then assign the result of our multiply function to a variable called product. We’ll then echo the value of product. In our example, the result will be 4.

$product = multiply(2,2);
echo $product;

Improving our function

With the introduction of type declarations, we can specify the type of values we are expecting to receive in our function. For example, what would happen if someone passed two instead of 2 to our function? Feel free to try it out before reading on.

In this instance, we are expecting the values passed to our function to be of int value. so we’ll declare our parameter types with placing the data type before the variables.

function multiply(int $a,int $b) {}

The purpose of this function is to return the product of the two integers. Given both values are whole numbers, the result is also going to be an integer. In addition to defining the input parameter types, we can also define the expected return value of the function, by adding :int after our parentheses.

function multiply(int $a,int $b): int {}

Here’s what our code looks like at this stage.

function multiply(int $a,int $b): int{
	return $a*$b;
}
$product = multiply(1,2);
echo $product;

This code works quite well when multiplying two numbers, but what will happen if we want to multiply 3 numbers? Easy. We’ll just create an extra parameter in our function.

function multiply(int $a,int $b,int $c): int{
    return $a*$b*$c;
}
$product = multiply(1,2,3);
echo $product;

There may be times where we won’t have all three arguments passed in. As our code stands, it will throw an error and stop executing. Let’s fix that by providing a default value for all 3 arguments. Since any number multiplied by 1 returns the number itself, we’ll set the default value of each argument to 1.

function multiply(int $a=1,int $b=1,int $c=1): int{
    return $a*$b*$c;
}
$product = multiply(1,2);
echo $product;

Notice how we have only passed in two arguments on line 4.

What would we do if we’re expecting 10,20 or 100 numbers? Obviously, we can create more arguments in our function, but that makes the code hard to read and maintain. Instead, let’s have a look at the splat operator.

the splat operator is written as ... and proceeded by the argument name.

The splat operator will take all the arguments passed in and packs them into an array. We can then use the array_product function to multiply all the numbers inside the array.

function multiply(int ...$ints): int{
    return array_product($ints);
}
$product = multiply(3,4);
echo $product;

This is much better, but what would happen if we don’t pass in any arguments? If array_product receives an empty array, it will return 1. This makes sense as 1 is the neutral number in multiplication. However in this instance, if we don’t receive any input, I would like to return 0 .

This can be accomplished by simply creating a variable named returnVal and assigning it a value of 0.

$returnVal = 0;

We will then use an if statement to check wether our ints array is empty. We will use the count function to check the number of items in our array. If count returns 0, we know our array is empty.

if (count($ints) !== 0) {}

Here’s what our revamped function looks like

function multiply(int ...$ints): int{
    $returnVal = 0;
    if (count($ints) !== 0){
        $returnVal = array_product($ints);
    }
    return $returnVal;
}
$emptyProduct = multiply();
// returns 0
$product = multiply(1,2);
// returns 2
$crazyProduct = multiply(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
// returns 2432902008176640000. This is most likely the correct answer.

I’m fairly happy with our code, but the if statement is making our code look a little bloated. Given this is a fairly simple if statement, I’m going to use a ternary operator to squeeze this statement in a single line.

return (count($ints) !== 0?array_product($ints):0);

Our ternary operator starts by checking wether a statement is true or false. This is the section before the ?. The true and false conditions are separated by the :. In this case, if ints is not empty, use array_product to multiply the contents of ints, otherwise return 0;

Once again, here’s our code after it’s facelift.

function multiply(int ...$ints): int{
    return (count($ints) !==0?array_product($ints):0);
}
$emptyProduct = multiply();
$product = multiply(1,2);
$crazyProduct = multiply(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);

Not bad. We’re almost done. Last thing I want to do, is make sure our product variables can safely be set. A big part of that, is catching and handling errors. To accomplish this, we’ll use the try and catch statements. We will use the TypeError exception with the catch statement, and use the getMessage method to output the failure.

This will give us an opportunity to gracefully recover from invalid data type inputs.

Here’s our first attempt at solving this problem:

<?php
    $integer = 2*2;
	echo $integer;

Here’s our improved code:

<?php
  function multiply(int ...$ints): int{
  	return (count($ints) !==0?array_product($ints):0);
  }
  try {
  	$product = multiply('two',2,5);
  } 
  catch (TypeError $ex){
  	echo $ex->getMessage();
    //output: multiply(): Argument #1 must be of type int, string given, called in /Users/smatrouh/Documents/Projects/Code Challenge/050722 - multiply.php on line 6
  }

Happy coding.

Leave A Comment

Your email address will not be published. Required fields are marked *