Given two numbers, the task is to multiply both numbers using PHP. Multiplying two numbers is a fundamental arithmetic operation.
Examples:
Input: x = 10, y = 5
Output: 50Input: x = 40, y = 4
Output: 160
Table of Content
Approach 1: Using the * Operator
The simplest way to multiply two numbers in PHP is by using the multiplication operator *.
<?php
function multiplyNums($num1, $num2) {
$result = $num1 * $num2;
return $result;
}
// Driver code
$num1 = 5;
$num2 = 8;
$product = multiplyNums($num1, $num2);
echo "Products: $product";
?>
Output
Products: 40
Approach 2: Using the bcmul() Function
The bcmul() function is used for arbitrary-precision multiplication, providing accurate results for large numbers.
<?php
function multiplyNums($num1, $num2) {
$result = bcmul($num1, $num2);
return $result;
}
// Driver code
$num1 = 12;
$num2 = 8;
$product = multiplyNums($num1, $num2);
echo "Products: $product";
?>
Output
Products: 96Approach 3: Using Custom Function for Multiplication
Create a custom function that multiplies two numbers without using the * operator.
<?php
function multiplyNums($num1, $num2) {
$result = 0;
for ($i = 0; $i < $num2; $i++) {
$result += $num1;
}
return $result;
}
// Driver code
$num1 = 12;
$num2 = 8;
$product = multiplyNums($num1, $num2);
echo "Product: $product";
?>
Output
Product: 96