0

I try to validate fields. Three fields that may only contain numbers. The fields have the variable names $num1, $num2, $num3. I have put them in an array and then I run preg_match but it does not work. How should I do?

$valnum = array (‘$num1’, ‘$num2’, ‘$num3’);
    if (preg_match('/[0-9]/', $valnum)){
echo $mycost;
}
    else {
echo 'You can only enter numbers';  
    }
3
  • [0-9] will only match a single digit. Also, preg_match takes a string as its second parameter, not an array. Commented Feb 15, 2012 at 21:59
  • 1
    @EtiennedeMartel Actually [0-9] will match any string with a number in it. Commented Feb 15, 2012 at 22:00
  • Are you using a word processing tool such as MS word to write your code? You have typographical quotes in your code which will not work. You should really consider using a text editor such as Notepad++ or GVim! Commented Feb 16, 2012 at 1:10

3 Answers 3

1

Consider using filter_var as it is desgined for this type of validation:

$array = array(1, 2, 'a', 'b');
var_dump(filter_var_array($array, FILTER_VALIDATE_INT));

Output:

array
  0 => int 1
  1 => int 2
  2 => boolean false
  3 => boolean false

http://php.net/manual/en/function.filter-var-array.php

Sign up to request clarification or add additional context in comments.

3 Comments

"numbers" may not = integers.
I use is_numeric () now but I'll try this solution too when I get time. Thank you.
@Dagon php.net/manual/en/filter.constants.php will show you available filter types. Number being one of them.
0
   is_numeric() 

would be a better approach

//worked up example:

<?php
$num1 = '1';
$num2 = '11';
$num3 = '11.11';

$mycost = '$99.99';

$valnum = array($num1,$num2,$num3);
$check = '';
foreach($valnum as $element){
    if(!is_numeric($element)){
        $check = 'bad';
        break;
    }
}

if($check=='bad'){
    echo 'You can only enter numbers';
}else{
    echo $mycost;
}

?>

returns 99.99

9 Comments

$valnum = array (‘$num1’, ‘$num2’, ‘$num3’); foreach ($valnum as $element) { if (is_numeric($element)) { echo $mycost; } else { echo 'You can only enter numbers'; } }
I get the error message "You can only enter numbers" when I enter something in the fields, even numbers.
I don't see how, sure they are all numbers? see worked up version above
Sorry, I wrote $valnum = array('$num1','$num2','$num3'); but It works fine when I write $valnum = array($num1,$num2,$num3);
I just wonder, shouldn't It work with'' around my variables in the array as well?
|
0

If you demand checking numeric input by preg_match() you should:

  • at first add ^ (start of string) and $ (end of string) meta characters to your regexp
  • add handling for floats
  • consider removing spaces from string (user may decide to input 1 800 instead of 1800)
  • use \d - escape sequence for decimal numbers group

So final regexp would look like: ~^\d+([.,]\d+)?$~.

You should rather use is_numeric() but according to manual it accepts "science format":

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.

Which I personally avoid, this function just allows to input too much and you have to worry about transformation to valid form.

There'are two nice functions intval() and floatval() with just a little example:

$numbers = array( '1.8', '3', 'hello');

foreach( $numbers as $i){
    var_dump( $i);
    var_dump( intval( $i));
    var_dump( floatval( $i));
    echo "\n";
}

And output:

string(3) "1.8"
int(1)
float(1.8)

string(1) "3"
int(3)
float(3)

string(5) "hello"
int(0)
float(0)

Which allows you to do this:

php > $str = "3.8";
php > $i = intval( $str);
php > var_dump( $i == $str);
bool(false)
php > $str = "3";
php > $i = intval( $str);
php > var_dump( $i == $str);
bool(true)

You also can use filter_var(), but those functions just doesn't work for me and I'd build function like this:

function get_integer( $input){
    if( $input === null){
         return null;
    }

    if( $input === ''){
         return null;
    }

    $i = intval( $input);
    if( $i != $input){
         return null;
    }

    return $i;
}

$myCol = get_integer( $_POST['foo']);
if( $myCol === null){
    die( 'You naughty boy!');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.