[PHP] Making sure a variable is an integer

Soldato
Joined
4 Jul 2004
Posts
2,647
Location
aberdeen
I know its just a simple function, can't remember or find what it is.

Need to make sure that for example ...
PHP:
$id = $_GET['id']
is always ONLY an integer. I've done it but it requires 3 if statements, i'm know i had a (built in) function that worked a while ago but can't remember it.

Thanks :D
 
You can't use is_int() because GET/POST input is always a string, but you can use this, shamefully nicked from the is_numeric() comments:

Code:
function is_whole_number($var){
  return (is_numeric($var)&&(intval($var)==floatval($var)));
}
:)
 
You can cast it ie

$four = '4'; //string
$four = (int) $four; // should be an int, let's check
var_dump($four); //prints int(4), job's a good'un

Col
 
In a sloppy fashion (imo):

Code:
<?php

$number = '5';
$number+0;

//$number is now an int

?>

intval() or typecasting (when used in a particular context) is the least sloppy.

Code:
<?php

function ReturnInt ($val)
{
    return (int) (($val / ($val - 5)) * 8);
}

?>
 
Thanks for your replies.

This is something I've never worked out with PHP... In Java or whatever, you always define if something is for example a string, int etc. How do you do this sort of thing in PHP?

When i set $example = "1", would that, like that, be a string? Or an integer?

Thanks
 
Chronicle said:
This is something I've never worked out with PHP... In Java or whatever, you always define if something is for example a string, int etc. How do you do this sort of thing in PHP?
You don't. PHP, unlike C#, Java et al, is not a strongly-typed language, so any variable can be of any type (and can change).
 
Chronicle said:
Thanks for your replies.

This is something I've never worked out with PHP... In Java or whatever, you always define if something is for example a string, int etc. How do you do this sort of thing in PHP?

When i set $example = "1", would that, like that, be a string? Or an integer?

Thanks

PHP just performs implicit type conversions when you need it to.

Code:
$int = 4;
$string = "5";

// casts the string to an int in order to compare the two:
var_dump($string > $int); // bool(true);
 
Back
Top Bottom