how to get length of integers in PHP ?

Viewed 98698

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?

10 Answers

By using the assertion library of Webmozart Assert we can use their build-in methods to validate the input.

  • Use integerish() to validate that a value casts to an integer
  • Use length() to validate that a string has a certain number of characters

Example

Assert::integerish($input);
Assert::length((string) $input, 10); // expects string, so we type cast to string

As all assertions in the Assert class throw an Webmozart\Assert\InvalidArgumentException if they fail, we can catch it and communicate a clear message to the user.

Example

try {
    Assert::integerish($input);
    Assert::length((string) $input, 10);
} catch (InvalidArgumentException) {
    throw new Exception('Please enter a valid phone number');
}

As an extra, it's even possible to check if the value is not a non-negative integer.

Example

try {
    Assert::natural($input);
} catch (InvalidArgumentException) {
    throw new Exception('Please enter a valid phone number');
}

I hope it helps

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

?>
Related