Jump to content

[SOLVED] If a variable is a number


Demonic

Recommended Posts

<?php

$num = 0;
$num2 = "0";
$num3 = "0gag";
$num4 = "egaa0";

function is_num($var) {
if( preg_match("/^[0-9]+$/", $var) ) {
	echo 'true<br />';
	return;
}
echo 'false<br />';
return;
}
is_num($num);
is_num($num2);
is_num($num3);
is_num($num4);
?>

 

I made this function and so far the results are:

true

true

false

false

 

Will this always be the case and most likely work in all conditions? Or do I have to go into more in depth checks?

 

Updated with:

<?php

$num = 0;
$num2 = "0";
$num3 = "0gag";
$num4 = "egaa0";
$num5 = true;
$num6 = array();
function is_num($var) {
if( @preg_match("/^[0-9]+$/", $var) ) {
	echo 'true<br />';
	return;
}
echo 'false<br />';
return;
}
is_num($num);
is_num($num2);
is_num($num3);
is_num($num4);
is_num($num5);
is_num($num6);
?>

 

Results are:

true

true

false

false

true

false

 

Looking good so far, is it safe to say this is an accurate function?

 

Link to comment
Share on other sites

It depends on WHAT you are really trying to test. For example this:

$num2 = "0";

is really a string. Also, your results above show that this:

$num5 = true;

returns true for being a number. That doesn't look correct to me. Also your function doesn't take into account numbers that are not integers (e.g. 1.5).

 

There are many built in functions for testing if a variable is a type of number:

is_numeric()

is_int()

is_float()

etc.

 

 

Link to comment
Share on other sites

It depends on WHAT you are really trying to test. For example this:

$num2 = "0";

is really a string. Also, your results above show that this:

$num5 = true;

returns true for being a number. That doesn't look correct to me. Also your function doesn't take into account numbers that are not integers (e.g. 1.5).

 

There are many built in functions for testing if a variable is a type of number:

is_numeric()

is_int()

is_float()

etc.

 

 

 

Regardless $_POST input form posts will end up as strings, and I want to check if its a number, so in my cause will that work? I was looking at 'is_numeric' that would work in this case then right? (Then again I don't want decimals)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.