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
https://forums.phpfreaks.com/topic/115504-solved-if-a-variable-is-a-number/
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.

 

 

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)

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.