Results 1 to 5 of 5

Thread: Check for numbers in variable RESOLVED

Hybrid View

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Aug 2002
    Location
    South Wales (UK)
    Posts
    83

    Check for numbers in variable RESOLVED

    What's the best way of checking that a variable only has numbers in it, so no letters or commas etc.
    Last edited by aaronskw; Sep 29th, 2003 at 06:41 AM.

  2. #2
    Use the is_numeric function.

    PHP Code:
    <?php

    $var1
    "12three"// alphanumeric
    $var2 "123"// numeric string
    $var3 123// integer

    if(is_numeric($var1))
    {
        echo 
    "this will not be echo'd because it is false";
    }

    if(
    is_numeric($var2))
    {
        echo 
    "this will be echo'd because it is true";
    }

    if(
    is_numeric($var3))
    {
        echo 
    "this will be echo'd because it is true";
    }

    ?>
    If its from an imput form or something that's going to be a little but "less then perfect", you might want to do some cleanup to remove trailing spaces etc. (trim)

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Aug 2002
    Location
    South Wales (UK)
    Posts
    83
    thnx for the reply, i'll give it a go.

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Aug 2002
    Location
    South Wales (UK)
    Posts
    83
    It seems there's no need to do a Trim for an input form, bonus!!!

    Thnx again.

  5. #5
    Frenzied Member
    Join Date
    Nov 1999
    Posts
    1,337
    careful as is_numeric will also detect this as numeric

    4e4 and 444 // those are both correct.

    you want this

    Code:
    if (preg_match ("/^([0-9]+)$/", $input_number)) {
    echo "true";
    } else {
    echo "false";
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width