HomeLanguagesPHP gmp_init() Function

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.

  • $num: The number you want to initialize as a GMP object. It can be provided as a string, an integer, or another GMP object.
  • $base: The base of the number representation. It can be specified as an integer from 2 to 62. If not provided or set to 0, the function will try to determine the base automatically based on the input string.

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




<?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




<?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

RELATED ARTICLES

4 COMMENTS

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS