PHP Program to Multiply Two Numbers
Last Updated :
02 Jan, 2024
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: 50
Input: x = 40, y = 4
Output: 160
Approach 1: Using the * Operator
The simplest way to multiply two numbers in PHP is by using the multiplication operator *.
PHP
<?php
function multiplyNums( $num1 , $num2 ) {
$result = $num1 * $num2 ;
return $result ;
}
$num1 = 5;
$num2 = 8;
$product = multiplyNums( $num1 , $num2 );
echo "Products: $product" ;
?>
|
Approach 2: Using the bcmul() Function
The bcmul() function is used for arbitrary-precision multiplication, providing accurate results for large numbers.
PHP
<?php
function multiplyNums( $num1 , $num2 ) {
$result = bcmul ( $num1 , $num2 );
return $result ;
}
$num1 = 12;
$num2 = 8;
$product = multiplyNums( $num1 , $num2 );
echo "Products: $product" ;
?>
|
Output
Products: 96
Approach 3: Using Custom Function for Multiplication
Create a custom function that multiplies two numbers without using the * operator.
PHP
<?php
function multiplyNums( $num1 , $num2 ) {
$result = 0;
for ( $i = 0; $i < $num2 ; $i ++) {
$result += $num1 ;
}
return $result ;
}
$num1 = 12;
$num2 = 8;
$product = multiplyNums( $num1 , $num2 );
echo "Product: $product" ;
?>
|
Share your thoughts in the comments
Please Login to comment...