Int or not Int. How to fix the code? - php

I would like the code below to return 'Int' the first time and 'Not int' the second time. Unfortunately it returns 'Not int' twice instead.
How can I fix this?
<?php
$test1='1';
if(is_int($test1)){
echo "Int";
}else{
echo "Not int";
}
echo "\n";
$test2='1a';
if(is_int($test2)){
echo "Int";
}else{
echo "Not int";
}
?>

By wrapping the number in quotation marks '1', you are declaring a string.
Instead you got to use $test1 = 1;.
By using the PHP ctype_digit() function, you can check if a string only contains digits.
You could also use the is_numeric() function, which also returns true if the string contains a exponential part like +0123.45e6 or a hex value 0xFF.

is_int - Find whether the type of a variable is integer
Because you put the number in quotes, it is a string. Therefore is_int = false
is_numeric — Finds whether a variable is a number or a numeric string
Because the string is actually a number, is_numeric will return true
So, change is_int to is_numeric and it works:
<?php
$test1 = '1';
if (is_numeric($test1))
{
echo 'Int';
}
else
{
echo 'Not int';
}
echo "\n";
$test2 = '1a';
if (is_numeric($test2))
{
echo 'Int';
}
else
{
echo 'Not int';
}
?>

Use ctype_digit() instead.
ctype_digit('1'); // True
ctype_digit('1a'); // False

change
$test1='1';
to
$test1=1;

Related

How to determine the type of a numerical value passed as a string without losing data or being converted to wrong datatype

I want to allow users to submit numerical values through an online form but I've ran into a problem trying to validate the correct datatype(integer or float) for the submitted value.
Lets say a user submits:
3.14
I cannot use is_float() because the user-value is technically a string.
floatval() would work, except when the user only supplies an integer floatval() still considers it a float instead of an integer.
gettype(floatval("3"))
returns float, but I need it to return integer.
I even tried checking if it was an integer like this:
is_int(floatval(3)) // returns false
But why does the above return false?
The below prints 3 as if it was an integer:
echo floatval(3)
Therefore, I need a function that can be able to tell the difference between a float and integer passed as a string so it doesn't
pass an integer off as a float.
doesn't truncate a float into an integer.
Pattern checking with regular expressions could possibly be a solution, but are there any other alternatives?
NOTE: I am not using classes or objects and I prefer not to if possible.
Convert it to a float and integer, then check if they're equal.
$i = intval($input);
$f = floatval($input);
if ($i == $f) {
$type = "int";
} else {
$type = "float";
}
Below function will solve your problem
function checkType($inputNumber){
if (strpos($inputNumber, '.') !== false) {
return 'Number is float';
} else {
return 'Number is integer';
}
}
echo checkType(3.5); o/p Number is float.
echo checkType(3); o/p Number is integer.
First of all, If you checking float then obviously it will only return true or false on float value weather or not it's a integer.
You are checking for float then how can you expect that it will return integer. Use intval() to check integer value.
<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34
echo intval('042'); // 42
echo intval(1e10); // 1410065408
echo intval('1e10'); // 1
Or you can do one thing you can check if dot(.) exist then check with floatval() and not then check with intval()
You can alos do something like following
<?php
$a = '1.6';
if(str_pos($a, '.') !== 'false){
$a = intval($a);
}else{
$a = floatval($a);
}

PHP - if condition match exact value including decimal

i am trying to match exact number with decimal. i have tried following but doesn't work
tried following code, but doesn't work with decimal.
<?php
$number=1.23;
$numbers=1.28;
if (is_float($number)==is_float($numbers))
{
echo 'matched';
}else{
echo 'not matched';
}
?>
please check where i am doing mistake or it's totally wrong way to do that. i have check above in PHP sites.
Use floatval (which returns the float value of the given variable) instead of is_float (which returns true if the given variable is a float and false if it isn’t).
You could simply make use of a strict matching operator === instead of floatval or is_float.
<?php
$number=1.23;
$numbers=1.28;
if($number === $numbers)
{
echo "Matched";
}
else { echo "No Match"; }

How can one check in PHP if a string can be converted into a whole number?

For instance, "000", "404", and "0523" can be converted into whole numbers in PHP, but "42sW" and "423 2343" cannot be converted into whole numbers.
Use the ctype_digit function. is_numeric will also permit floating point values.
$numArray = array("1.23","156", "143", "1w");
foreach($numArray as $num)
{
if (ctype_digit($num)) {
// Your Convert logic
} else {
// Do not convert print error message
}
}
}
PHP's is_numeric() can determine if a given param is a number or a number string. Have a read through the manual for some examples.
ctype_digit should be what you're looking for.
42Sw can be converted to a number by using intval()
echo intval("42sW"); // prints 42
use is_numeric():
if (is_numeric("string")) {
echo "This can be converted to a number";
}
You could try something like this.
<?php
if (is_numeric($string)) {
//functions here
}
else{
//functions2 here
}
?>
$test = "42sW";
if (ctype_digit($test)) {
echo "The string $test consists of all digits.\n";
} else {
echo "The string $test does not consist of all digits.\n";
}
//OR
is_numeric($test); // false

Validating whether $_REQUEST contents is an int

I am trying to do a basic operation: to check whether string is a number.
This does not work:
$qty = $_REQUEST[qty];
if (is_int($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
This one does:
$qty = 1;
if (is_int($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
$_REQUEST[qty] is posted with AJAX request ($.post). $_REQUEST[qty] is NOT empty and contains only number (1).
is_numeric() is not going to work, since it treats 1e4 as a number.
is_int will only return true if the variable is of integer type.
if you are trying to test if the variable contains a string which represents a number,
use:
is_numeric("1");
source: http://php.net/manual/en/function.is-int.php
EDIT:
use ctype_digit() to check for every character in the string if it's a number to rule out "1e4"
If you want to check for the presence of digits only, you can use ctype_digit .
try "is_numeric()" instead of "is_int"...
i think that u r getting a String from your Request...
and is_int really checks wether a given object is a integer... But it isn't -> it's a String.
is_numeric just checks, wether a object is convertable into an integer. If so, it returns true, otherwise false...
$qty = $_REQUEST[qty];
if (is_numeric($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
PS: Use $_POST[] or $_GET[] insetead of $_REQUEST[] ;)
You mention you cannot use is_numeric because it treats 1e4 as a number. Well, 1e4 is a number. Specifically 1 * 10^4.
You could use is_int(intval($_REQUEST['qty'])), but as intval always returns an int (0 on failure or empty input) you run the risk of false positives. However, combined with is_numeric or filter_var you should be on pretty solid ground.
Actually, all $_REQUEST (as well as $_GET, $_POST, etc) values are always strings.
When $qty is $_REQUEST[qty] it's an string, not an integer. When $qty is 1, it's already an integer.
Use intval function to convert it to an integer. But as you say, you only want to find out whether it's an integer or not, so use floatval to convert it, then check if they are equal:
if (intval($qty) == floatval($qty)) {
echo "Ok!";
} else {
echo "error";
}
Do a not-identical comparison­Docs while using the string and integer cast:
if ($qty !== (string)(int)$qty) {
echo "error";
} else {
echo "ok";
}
This is basically literal: As all incoming variables are strings, you can't check them being an integer, unless you cast them to an integer and then back to string. Wrap it into a function if it's to hard to grasp in inline code what it does:
/**
* string is integer value?
*
* #return bool
*/
function is_int_string($string)
{
return $string === (string)(int)$string;
}
$qty = $_REQUEST[qty];
if (is_int_string($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
HTTP is a text protocol, so there is only string in the beginning.
I decided to go with preg_match().
if (!preg_match("/^[0-9]+$/", $_REQUEST[qty])) {}

How can I check a value entered in a field on my form is a number?

How can I check a value entered in a field on my form is a number?
ex:
$values = array(1,20,10);
you can use function :
is_numeric() — Finds whether a variable is a number or a numeric string ..
for example :
<?php
$tests = array(
"42",
1337,
"1e4",
"not numeric",
array(),
9.1
);
foreach ($tests as $element) {
if (is_numeric($element)) {
echo "'{$element}' is numeric", PHP_EOL;
} else {
echo "'{$element}' is NOT numeric", PHP_EOL;
}
}
?>
The above example will output:
'42' is numeric
'1337' is numeric
'1e4' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric
source : http://php.net/manual/en/function.is-numeric.php
This might help:
http://php.net/manual/en/function.is-numeric.php
You could check the input from the form using is_numeric().
If all you want to know is if it is a number, then PHP has a function called is_numeric that returns true if it's numeric.
However, if you want to know if something is an integer, don't use is_int. Use filter_var($variable, FILTER_VALIDATE_INT).
If you want to know if something is a float (such as 1.00123): filter_var($variable, FILTER_VALIDATE_FLOAT).

Categories