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?
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
?>
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)
(int)
converts a value to an integer.
<?php
$test = "1";
echo gettype((int)$test);
?>
$ php test.php
integer
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.
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
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()