PHP intval() behaviour? - php

This sounds to strange to me:
$test_1 = 'string';
$test_2 = '0';
var_dump(intval($test_1)); // Output: int 0
var_dump(intval($test_2)); // Output: int 0
$can_cast = intval($test_2) ? 'sure' : 'nope'; // Wrong!!!
So with a string to int conversion intval returns 0. Fine, but it returns 0 also when the string actually can be casted to zero (because is zero) thus valid.
How can one can distinguish between both (allows '0' as string and deny 'string')?
EDIT: ok let me say i know i can use is_numeric. But is_numeric('2.3') returns true, so it can't help. And:
$test = '0';
var_dump(is_numeric($test) && intval($test)); // Fail!!!

You could do a ctype_digit check before you cast (if you want only positive numbers). Alternatively you could do an integer validation using filter_var and FILTER_VALIDATE_INT. The integer validation will also check integer semantics, i.e. it will ensure that the integer is within the allowed range. You can also customize it for your needs through several options.

Related

Trouble working with the value of a checkbox server side [duplicate]

I am new to PHP. I am implementing a script and I am puzzled by the following:
$local_rate_filename = $_SERVER['DOCUMENT_ROOT']."/ghjr324l.txt";
$local_rates_file_exists = file_exists($local_rate_filename);
echo $local_rates_file_exists."<br>";
This piece of code displays an empty string, rather than 0 or 1 (or true or false). Why? Documentation seems to indicate that a boolean value is always 0 or 1. What is the logic behind this?
Be careful when you convert back and forth with boolean, the manual says:
A boolean TRUE value is converted to the string "1". Boolean FALSE is
converted to "" (the empty string). This allows conversion back and
forth between boolean and string values.
So you need to do a:
echo (int)$local_rates_file_exists."<br>";
About converting a boolean to a string, the manual actually says:
A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.
A boolean can always be represented as a 1 or a 0, but that's not what you get when you convert it to a string.
If you want it to be represented as an integer, cast it to one:
$intVar = (int) $boolVar;
The results come from the fact that php implicitly converts bool values to strings if used like in your example. (string)false gives an empty string and (string)true gives '1'. That is consistent with the fact that '' == false and '1' == true.
If you wanna check if the file exists when your are not sure of the return type is true/false or 0/1 you could use ===.
if($local_rates_file_exists === true)
{
echo "the file exists";
}
else
{
echo "the doesnt file exists";
}

Why is my If statement accepting an incorrect String condition in PHP?

I am very confused, because PHP accepts the below condition.
<?php
$b = true;
if($b == 'anything')
echo 'ok';
else
echo 'no';
?>
Well, PHP displays ok. I still don't understand how is it possible.
Maybe, you can clarify it for me.
this should work for you
$b = true;
if($b === 'hello')
echo 'ok';
else
echo 'no';
when using == php will only checks if values are equal, without comparing the values types, when first value is a bool, php will convert both sides to bool, converting any string but the empty string '' and the string '0' will return true, that's why you have to use ===
follow this link to understand comparison in php
Php is not a strictly typed language so the value in the second half of the IF statement is considered a Truthy value. If you want to complare types as well use the "===" comparison. Take a look at the truthy table on this page. http://php.net/manual/en/types.comparisons.php
According to the PHP manual on comparison operators (http://php.net/manual/en/language.operators.comparison.php) == checks for "equalness" whereas === checks for identity (which practically means it is of same TYPE and of same VALUE).
When comparing (for equalness) a bool and a string, the string gets casted to a bool. According to the docs:
When converting to boolean, the following values are considered FALSE:
* the boolean FALSE itself
* the integer 0 (zero)
* the float 0.0 (zero)
* the empty string, and the string "0"
* an array with zero elements
so your string 'anything' becomes true.

PHP printed boolean value is empty, why?

I am new to PHP. I am implementing a script and I am puzzled by the following:
$local_rate_filename = $_SERVER['DOCUMENT_ROOT']."/ghjr324l.txt";
$local_rates_file_exists = file_exists($local_rate_filename);
echo $local_rates_file_exists."<br>";
This piece of code displays an empty string, rather than 0 or 1 (or true or false). Why? Documentation seems to indicate that a boolean value is always 0 or 1. What is the logic behind this?
Be careful when you convert back and forth with boolean, the manual says:
A boolean TRUE value is converted to the string "1". Boolean FALSE is
converted to "" (the empty string). This allows conversion back and
forth between boolean and string values.
So you need to do a:
echo (int)$local_rates_file_exists."<br>";
About converting a boolean to a string, the manual actually says:
A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.
A boolean can always be represented as a 1 or a 0, but that's not what you get when you convert it to a string.
If you want it to be represented as an integer, cast it to one:
$intVar = (int) $boolVar;
The results come from the fact that php implicitly converts bool values to strings if used like in your example. (string)false gives an empty string and (string)true gives '1'. That is consistent with the fact that '' == false and '1' == true.
If you wanna check if the file exists when your are not sure of the return type is true/false or 0/1 you could use ===.
if($local_rates_file_exists === true)
{
echo "the file exists";
}
else
{
echo "the doesnt file exists";
}

How to compare string or int type?

if($_GET['choice'] == (int))
or
if($_GET['choice'] == (string))
I got an error.
All GET parameters are strings. If you want to be certain that it's an integer in the string then you should sanitize it.
To check if the string $_GET['choice'] may be represented as an integer, use ctype_digit(), eg
if (ctype_digit($_GET['choice'])) {
// integer
}
You're doing it wrong. Your example shows CASTING:
$var = (int)"15"; // casts the string 15 as an integer
If you want to compare if something is an INTEGER, you can use the is_int() function in PHP. There are other operators that will do this for strings, arrays, etc;
http://us2.php.net/manual/en/function.is-int.php

is_int and GET or POST

Why does is_int always return false in the following situation?
echo $_GET['id']; //3
if(is_int($_GET['id']))
echo 'int'; //not executed
Why does is_int always return false?
Because $_GET["id"] is a string, even if it happens to contain a number.
Your options:
Use the filter extension. filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT) will return an integer typed variable if the variable exists, is not an array, represents an integer and that integer is within the valid bounds. Otherwise it will return false.
Force cast it to integer (int)$_GET["id"] - probably not what you want because you can't properly handle errors (i.e. "id" not being a number)
Use ctype_digit() to make sure the string consists only of numbers, and therefore is an integer - technically, this returns true also with very large numbers that are beyond int's scope, but I doubt this will be a problem. However, note that this method will not recognize negative numbers.
Do not use:
is_numeric() because it will also recognize float values (1.23132)
Because HTTP variables are always either strings, or arrays. And the elements of arrays are always strings or arrays.
You want the is_numeric function, which will return true for "4". Either that, or cast the variable to an int $foo = (int) $_GET['id']...
Checking for integers using is_int($value) will return false for strings.
Casting the value -- is_int((int) $value) -- won't help because strings and floats will result in false positive.
is_numeric($value) will reject non numeric strings, but floats still pass.
But the thing is, a float cast to integer won't equal itself if it's not an integer. So I came up with something like this:
$isInt = (is_numeric($value) && (int) $value == $value);
It works fine for integers and strings ... and some floating numbers.
But unfortunately, this will not work for some float integers.
$number = pow(125, 1/3); // float(5) -- cube root of 125
var_dump((int) $number == $number); // bool(false)
But that's a whole different question.
How i fixed it:
$int_id = (int) $_GET["id"];
if((string)$int_id == $_GET["id"]) {
echo $_GET["id"];
}
It's probably stored as a string in the $_GET, cast it to an int.
Because $_GET is an array of strings.
To check if the get parameter contains an integer you should use is_numeric()
Because $_GET['id'] is a string like other parts of query string. You are not converting it to integer anywhere so is_int return false.
The dirty solution I'm using is this:
$val = trim($_GET['id']);
$cnd = ($val == (int)$val);
echo $cnd ? "It's an int" : "Not an int";
Apart from the obvious (ugly code that hides its workings behind specifics of the php engine), does anybody know cases where this goes wrong?
Prabably best way to check if value from GET or POST is integer is check by preg_match
if( preg_match('/^[0-9]+$/', $_GET['id'] ){
echo "is int";
}
You can possibly try the intval() which can be used to test the value of your var. e.g
If(intval($_GET['ID']==0)
The function will check if the var is integer and return TRUE if not FALSE

Categories