Open In App

PHP gmp_init() Function

The gmp_init() function is an inbuilt function in PHP that is used to create a GMP number from different data types, including strings, integers, or other GMP objects. It’s commonly used when you want to start performing arithmetic operations on large numbers without losing precision.

Syntax:



gmp_init( int|string $num, int $base = 0 ): GMP

Parameters: This function accepts two parameters that are described below.

Return Value: The gmp_init() function returns a GMP resource that represents the initialized number.



Program 1: The following program demonstrates the gmp_init() function.




<?php
      
$number = gmp_init("12345");
var_dump($number);
?>

Output:

object(GMP)#1 (1) {
["num"]=>
string(5) "12345"
}

Program 2: The following program demonstrates the gmp_init() function.




<?php
    
$hexNumber = "1A3B5";
$decimalNumber = 123456789;
  
$gmpHex = gmp_init($hexNumber, 16);
$gmpDecimal = gmp_init($decimalNumber);
  
// Perform arithmetic operations on GMP numbers
$sum = gmp_add($gmpHex, $gmpDecimal);
$product = gmp_mul($gmpHex, $gmpDecimal);
  
$sumAsString = gmp_strval($sum);
$productAsString = gmp_strval($product);
  
echo "Hex + Decimal = $sumAsString\n";
echo "Hex * Decimal = $productAsString\n";
  
?>

Output:

Hex + Decimal = 123564234
Hex * Decimal = 13264814694105

Reference: https://www.php.net/manual/en/function.gmp-init.php


Article Tags :