Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (int) $_GET['page'] mean in PHP?

Tags:

php

int

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?

like image 958
Simon Suh Avatar asked Oct 29 '11 20:10

Simon Suh


4 Answers

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".

like image 160
KingCrunch Avatar answered Sep 22 '22 15:09

KingCrunch


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

?>

like image 41
John Avatar answered Sep 22 '22 15:09

John


(int) converts a value to an integer.

<?php
$test = "1";
echo gettype((int)$test);
?>

$ php test.php
integer
like image 29
Griffin Avatar answered Sep 23 '22 15:09

Griffin


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)
like image 36
Cas Bloem Avatar answered Sep 22 '22 15:09

Cas Bloem