Home » Php » how to get length of integers in PHP ?

how to get length of integers in PHP ?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I want to get the length of integer values for validation in PHP.
Example:
Mobile numbers should be only 10 integer values. It should not be more than 10 or less than 10 and also it should not be included of alphabetic characters.

How can I validate this?

How to&Answers:
if (preg_match('/^\d{10}$/', $string)) {
  // pass
} else {
  // fail
}

Answer:

$num_length = strlen((string)$num);
if($num_length == 10) {
    // Pass
} else {
    // Fail
}

Answer:

This will work for almost all cases (except zero) and easily coded in other languages:

$length = ceil(log10(abs($number) + 1)

Answer:

In my opinion, the best way is:

$length = ceil(log10($number))

A decimal logarithm rounded up is equal to length of a number.

Answer:

If you are using a web form, make sure you limit the text input to only hold 10 characters as well to add some accessibility (users don’t want to input it wrong, submit, get a dialog about their mistake, fix it, submit again, etc.)

Answer:

Use intval function in loop,
See this example

<?php
  $value = 16432;
  $length=0;
  while($value!=0) {
   $value = intval($value/10);
   $length++
  }
  echo "Length of Integer:- ".$length;
 ?>

Answer:

$input = "03432 123-456"; // A mobile number (this would fail)

$number = preg_replace("/^\d/", "", $number);
$length = strlen((string) $number);

if ($number == $input && $length == 10) {
    // Pass
} else {
    // Fail
}

Answer:

If you are evaluating mobile numbers (phone numbers) then I would recommend not using an int as your chosen data type. Use a string instead because I cannot forsee how or why you would want to do math with these numbers. As a best practice, use int, floats, etc, when you want/need to do math. Use strings when you don’t.

Answer:

From your question, “You want to get the lenght of an integer, the input will not accept alpha numeric data and the lenght of the integer cannot exceed 10. If this is what you mean; In my own opinion, this is the best way to achieve that:”

<?php

$int = 1234567890; //The integer variable

    //Check if the variable $int is an integer:
if (!filter_var($int, FILTER_VALIDATE_INT)) { 
    echo "Only integer values are required!";
    exit();
} else {
    // Convert the integer to array
    $int_array  = array_map('intval', str_split($int));
    //get the lenght of the array
    $int_lenght = count($int_array);
}
    //Check to make sure the lenght of the int does not exceed or less than10
    if ($int_lenght != 10) {
    echo "Only 10 digit numbers are allow!";
    exit();
} else {
     echo $int. " is an integer and its lenght is exactly " . $int_lenght;
    //Then proceed with your code
}

    //This will result to: 1234556789 is an integer and its lenght is exactly 10

?>