I tried looking up (int) but could only find documentation for the function int() in the PHP manual.
Could someone explain to me what the above code does, and exactly how it works?
You can find it in the manual in the section type juggling: type casting. (int) casts a value to int and is a language construct, which is the reason that it looks "funny".
It convert (tries at least) whatever the value of the variable is to a integer. If there are any letter etc, in front it will convert to a 0.
<?php
$var = '1a';
echo $var; // 1a
echo (int) $var; //1
$var2 = 'a2';
echo $var2; //a2
echo (int) $var2; // 0
?>
(int) converts a value to an integer.
<?php
$test = "1";
echo gettype((int)$test);
?>
$ php test.php
integer
Simple example will make you understand:
var_dump((int)8);
var_dump((int)"8");
var_dump((int)"6a6");
var_dump((int)"a6");
var_dump((int)8.9);
var_dump((int)"8.9");
var_dump((int)"6.4a6");
Result:
int(8)
int(8)
int(6)
int(0)
int(8)
int(8)
int(6)
In PHP, (int) will cast the value following it to an int.
Example:
php > var_dump((int) "5");
int(5)
I believe the syntax was borrowed from C.
What you are looking at there is known as type casting - for more information, see the manual page on type juggling.
The above piece of code casts (or converts) $_GET['page'] to an integer.
this kind of syntax (int) is called type casting. Basically it takes the variable following it and tries to force it into being an int
(int) is same as int()
see
http://php.net/manual/en/language.types.integer.php
it casts the variable following it to integer. more info from documentation:
http://php.net/manual/en/language.types.type-juggling.php
Type casting in PHP works much as it does in C: the name of the
desired type is written in parentheses before the variable which is to
be cast.
The casts allowed are:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array (object) - cast to object
(unset) - cast to NULL
Related
I've seen some code written like this, and I'm really curious what it does and what it's for. Sorry for the unclear title, I appreciate all answers!
Edit: In particular I'm curious about the (string) $variable part
It's called type casting
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
<?php
$foo = 10; // $foo is an integer
$bar = (boolean) $foo; // $bar is a boolean
?>
The casts allowed are:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
(unset) - cast to NULL (PHP 5)
In your specific example a variable was being cast to a string before being passed as a parameter to testFunction()
It is a function call with an argument. In this case, a variable $variable has been cast to a string for the argument.
I have a url that will look as follows.
post/:id
I am exploding the $_SERVER['REQUEST_URI'];
and I need to make the $uri[2] is numerical so I can do things like
$next = $uri[2]++;
I have tried is_numeric but of course the request_uri is a string (broken into an array of strings).
Can I type cast in php to integer?
$int = (int) $uri[2];
You just have to convert from string to integer.
Have you tried intval(): http://php.net/manual/en/function.intval.php?
int intval(mixed $var [, int $base = 10 ])
"Returns the integer value of var, using the specified base for the conversion (the default is base 10). intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1."
UPDATE
Having wondered what the difference between (int) $string and intval($string) is, there are some interesting comments on previous SO questions;
(int) is upto 600% faster
intval makes it easier to typecast within other functions
intval has the benefit of changing base (although this is fairly obscure)
intval is more readable (tho this is obviously very subjective)
Is there any particular difference between intval and casting to int - `(int) X`?
When should one use intval and when int
http://hakre.wordpress.com/2010/05/13/php-casting-vs-intval/
Just to clarify both David and ChrisW are correct. Those are two ways of doing it as described at http://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting
<?php
$str = '100';
var_dump( $str ); // string(3) "100"
// http://php.net/manual/en/function.intval.php
var_dump( intval($str) ); // int(100)
// http://php.net/manual/en/language.types.type-juggling.php
var_dump( (int) $str ); // int(100)
?>
you can just take it as a number from url passing argument in as a $_GET request.
Or pass through as a $_POST request.
But in the case of $_POST request we cann't pass the value to url. if you want you can using $_SERVER['REQUEST_URI'] and convert to (int) $_GET['pid'].
In PHP you can typecast something as an object like this; (object) or you can use settype($var, "object") - but my question is what is the difference between the two?
Which one is more efficient / better to use? At the moment I find using (object) does the job, but wondering why there is a settype function as well.
Casting changes what the variable is being treated as in the current context, settype changes it permanently.
$value = "100"; //Value is a string
echo 5 + (int)$value; //Value is treated like an integer for this line
settype($value,'int'); //Value is now an integer
Basically settype is a shortcut for:
$value = (type)$value;
settype() alters the actual variable it was passed, the parenthetical casting does not.
If you use settype on $var to change it to an integer, it will permanently lose the decimal portion:
$var = 1.2;
settype($var, "integer");
echo $var; // prints 1, because $var is now an integer, not a float
If you just do a cast, the original variable is unchanged.
$var = 1.2;
$var2 = (integer) $var;
echo $var; // prints 1.2, because $var didn't change type and is still a float
echo $var2; // prints 1
It's worth mentioning that settype does NOT change the variable type permanently. The next time you set the value of the variable, PHP will change its type as well.
$value = "100"; //Value is a string
echo 5 + (int)$value; //Value is treated like an integer for this line
settype($value,'int'); //Value is now an integer
$value = "Hello World"; //Now value is a string
$value = 7; // Now value is an integer
Type Juggling can be frustrating but if you understand what's happening and know your options it can be managed. Use var_dump to get the variables type and other useful info.
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
How can I cast to integer in PHP using only 1 or two chars?
If I have the operation $a = (int) $b; it will result using those two (or one) chars:
$a = <*insert the needed 1 or 2 chars*> $b;
I need only to cast to integer. Thank you.
Prefix a + (the unary plus):
$a=+$b
A pretty common trick for code-golfing that also works in PowerShell and other languages.
$ php -r "var_dump('4');"
string(1) "4"
$ php -r "var_dump(+'4');"
int(4)
$a = sprintf("%02d", $b);
If you need to pad it with something other than zero, replace the zero with the character you need.
You can make a function, I guess. Of other type of shorter cast I'm unaware.
function z($i)
{
return (int)$i;
}
$a = z($b);