Jump to content

is_numeric returning false on '0'


bugzy

Recommended Posts

Newbie question guys...

 

 

On my form

 

<?php<input type="text" name="item_stock" size="3" value="<?php if(isset($_POST['submit']) AND is_numeric($_POST['item_stock'])) { echo $item_stock; } ?>

 

I have this validation

 

then

 

<?php

$item_stock = me_mysql_prep(trim($_POST['item_stock']));


//validation

if(!is_numeric($_POST['item_stock']) AND !empty($_POST['item_stock']))
{
	$item_sto = '';
}
else
{
	$item_sto = "has stock";
}



?>

 

 

 

On the validation, it keeps telling me that '0' is not numeric. I also tried using is_int.. but it's not working also..

 

Anyone?

Link to comment
https://forums.phpfreaks.com/topic/266143-is_numeric-returning-false-on-0/
Share on other sites

You need to ues :

 

if(!is_numeric($_POST['item_stock']) || !empty($_POST['item_stock']))

 

ie if not a number OR is empty = no stock

 

However, the value 0 returns a positive result so :

 

if(!is_numeric($_POST['item_stock']) || !empty($_POST['item_stock']) || $_POST['item_stock']==0) {

echo "no stock";

}

If you're trying to validate that a field contains only the digits 0-9, you should be using ctype_digit, since is_numeric() will return TRUE for '0XABCDEF' (hexadecimal number) as well as 83.956e45 (exponential notation).

If you're trying to validate that a field contains only the digits 0-9, you should be using ctype_digit, since is_numeric() will return TRUE for '0XABCDEF' (hexadecimal number) as well as 83.956e45 (exponential notation).

 

Guys the problem is not is_numeric..

 

"0" digit will always return true using the empty function of php. I have tried

 

if != "";

 

Not working also.. Any other good alternative for empty function??

For this situation I typically use this combination:

 

if(!ctype_digit($_POST['item_stock']) || !($_POST['item_stock'] > 0))

 

That's for situations where I want an integer greater than 0.  The first check excludes anything other than positive integers, but still allows "" and "0".  The second check excludes "" and "0".  If you do this a lot you can make a function for it.

 

If this is a text input then I would also use trim() first, because a lot of people add space into text inputs boxes.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.