I did some benchmarking and your method here is alot slower then using the actual gettype(); (Using php 5.3.4)
gettype
(PHP 4, PHP 5)
gettype — Retourne le type de la variable
Description
Retourne le type de la variable var. Pour vérifier le type de la variable, vous pouvez utiliser les fonctions is_*.
Liste de paramètres
- var
-
La variable à analyser.
Valeurs de retour
Les chaînes de caractères que peut retourner la fonction sont les suivantes :
Exemples
Exemple #1 Exemple avec gettype()
<?php
$data = array(1, 1., NULL, new stdClass, 'foo');
foreach ($data as $value) {
echo gettype($value), "\n";
}
?>
L'exemple ci-dessus va afficher quelque chose de similaire à :
integer double NULL object string
Voir aussi
- settype() - Affecte un type à une variable
- get_class() - Retourne la classe d'un objet
- is_array() - Détermine si une variable est un tableau
- is_bool() - Détermine si une variable est un booléen
- is_float() - Détermine si une variable est de type nombre décimal
- is_int() - Détermine si une variable est de type nombre entier
- is_null() - Indique si une variable vaut NULL
- is_numeric() - Détermine si une variable est un type numérique
- is_object() - Détermine si une variable est de type objet
- is_resource() - Détermine si une variable est une ressource
- is_scalar() - Indique si une variable est un scalaire
- is_string() - Détermine si une variable est de type chaîne de caractères
- function_exists() - Indique si une fonction est définie
- method_exists() - Vérifie que la méthode existe pour une classe
Wilson212
01-Jul-2011 09:20
langpavel at phpskelet dot org
01-Jun-2011 10:20
This function returns string representation of type. This is generalization of get_class(). I try to order is_* tests by density of occurence, but is bad idea to use result of this call in conditions for performance reasons, usefull and better than gettype for debugging messages.
Note, that last line should not be never executed.
Also has no sense to make input parameter optional.
<?php
function get_type($var)
{
if(is_object($var))
return get_class($var);
if(is_null($var))
return 'null';
if(is_string($var))
return 'string';
if(is_array($var))
return 'array';
if(is_int($var))
return 'integer';
if(is_bool($var))
return 'boolean';
if(is_float($var))
return 'float';
if(is_resource($var))
return 'resource';
//throw new NotImplementedException();
return 'unknown';
}
?>
Crysis nerd
19-Dec-2010 07:40
I wanted to compare the type of 2 vars.
1st method: Use this Funktion (gettype) and compare with ==
2nd method: Compare every type per is_[type]
Here a little Benchmark:
(I had to break line twice..)
<?php
$var1 = "Hallo";
$var2 = "Käsekuchen";
$var3 = 3.141526;
$Start = microtime(true);
for($i=0;$i<10000;$i++)
{
if(is_bool($var1)&&is_bool($var2)||is_int($var1)&&
is_int($var2)||is_string($var1)&&is_string($var2)||
is_object($var1)&&is_object($var2)||is_array($var1)
&&is_array($var2))
{
//same
}
if(is_bool($var3)&&is_bool($var2)||is_int($var3)&&
is_int($var2)||is_string($var3)&&is_string($var2)||
is_object($var3)&&is_object($var2)||is_array($var3)
&&is_array($var2))
{
//same
}
}
$time = microtime(true)-$Start;
echo "Zeit fuer if abfrage: ".$time."<br>";
$Start = microtime(true);
for($i=0;$i<10000;$i++)
{
if(gettype($var1)==gettype($var2))
{
//same
}
if(gettype($var3)==gettype($var2))
{
//same
}
}
$time = microtime(true)-$Start;
echo "Zeit fuer funktion : ".$time;
?>
Output:
Zeit fuer if abfrage: 0.0257611274719
Zeit fuer funktion : 0.0139331817627
So the function isnt so slow...
Lukas
PPKu-N0-SPAM-schy at mediasoft-berlin dot de
29-Nov-2010 07:57
After some testing I found a bug in my function "myGetType":
The check for "is_callable" was done before "is_string", so that something like <?php echo myGetType("max"); ?> would output: "function reference" instead of "string"
"is_callable" and "is_string" can't be checked together in this method, so I've removed the check for is_callable because it's a very rare usage case and if it's a valid string the check for is_callable never executes because is_string would be reached first (or vice-versa).
So here is the new function without "is_callable"-Check:
<?php
/**
* Returns the type of the var passed.
*
* @param mixed $var Variable
* @return string Type of variable
*/
function myGetType($var)
{
if (is_array($var)) return "array";
if (is_bool($var)) return "boolean";
if (is_float($var)) return "float";
if (is_int($var)) return "integer";
if (is_null($var)) return "NULL";
if (is_numeric($var)) return "numeric";
if (is_object($var)) return "object";
if (is_resource($var)) return "resource";
if (is_string($var)) return "string";
return "unknown type";
}
?>
SoN9ne at gmail dot com
08-Jun-2010 01:32
This is my work around for the gettype warning. Hope some find it useful.
<?php
/**
* Returns the type of the passed var
* - PHP warns against using gettype(), this is my workaround
*
* @param mixed $var
* @return string
*/
function myGetType($var)
{
if (is_array($var)) return "array";
if (is_bool($var)) return "boolean";
if (is_callable($var)) return "function reference";
if (is_float($var)) return "float";
if (is_int($var)) return "integer";
if (is_null($var)) return "NULL";
if (is_numeric($var)) return "numeric";
if (is_object($var)) return "object";
if (is_resource($var)) return "resource";
if (is_string($var)) return "string";
return "unknown type";
}
?>
[EDITOR thiago NOTE: Code has been updated by PPKu-N0-SPAM-schy at mediasoft-berlin dot de]
skatebiker at hotmail dot com
22-Feb-2008 06:51
In some rare cases a class instance object returns false when an object but gettype() returns "object".
<?php
$x = new classvar();
$save = serialize($x);
// ......
$obj = unserialize($save);
// here sometimes is_object() returns FALSE
if (is_object($x) || gettype($x) === "object")
{
// ... do something
}
?>
andrey at php dot net
17-Jul-2007 12:08
The function returns "unicode" for Unicode strings in PHP6.
sneskid at hotmail dot com
05-Mar-2007 02:56
I wrote my own gettype function by just using the default is_? functions, but it took twice as long as gettype... So I decided to use gettype with a twist.
Taking the warnings about gettype to heart, and depending on your custom needs, it's worthwhile to dynamically test the gettype result with a known variable, and link the result to a predefined result. Like so:
<?php
/*
dynamically create an array by using known variable types
link with a predefined value
*/
$R=array();
$R[gettype(.0)]='number';
$R[gettype(0)]='number';
$R[gettype(true)]='boolean';
$R[gettype('')]='string';
$R[gettype(null)]='null';
$R[gettype(array())]='array';
$R[gettype(new stdClass())]='object';
// what is
function wis_($v){
global $R;
return $R[gettype($v)];
}
echo wis_('hello') . '<br/>'; // "string"
echo wis_(24) . '<br/>'; // "number"
echo wis_(0.24) . '<br/>'; // "number"
echo wis_(null) . '<br/>'; // "null"
echo wis_($R) . '<br/>'; // "array"
?>
You won't need to worry about changes in gettype's return strings in future versions.
If the result evaluates to false then you know the variable tested is some "other" type.
I also find these useful
<?php
function is_num($v){return (is_int($v) || is_double($v));}
function is_box($v){return (is_array($v)||is_object($v));}
echo is_num(null) . '<br/>'; // false
echo is_num(false) . '<br/>'; // false
echo is_num('123') . '<br/>'; // false
echo is_num(123) . '<br/>'; // true
echo is_num(123.0) . '<br/>'; // true
?>
gilthansNOSPAM at gmail dot com
11-Sep-2005 03:18
NaN and #IND will return double or float on gettype, while some inexistent values, like division by zero, will return as a boolean FALSE. 0 by the 0th potency returns 1, even though it is mathematically indetermined.
<?php
$number = 5/0;
$number2 = sqrt(-3);
$number3 = pow(0, 0);
$number4 = 0/0;
echo $number."<br />";
echo $number2."<br />";
echo $number3."<br />";
echo $number4."<br />";
echo "<br />";
echo gettype($number)."<br />";
echo gettype($number2)."<br />";
echo gettype($number3)."<br />";
echo gettype($number4);
?>
This will return:
-1.#IND
1
boolean
double
integer
boolean
0
1
1
0
PHP Warning: Division by zero in C\test.php on line 2 PHP Warning: Division by zero in C:\test.php on line 5
matt at appstate
16-Dec-2004 12:10
Here is something that had me stumped with regards to gettype and is_object.
Gettype will report an incomplete object as such, whereas is_object will return FALSE.
<?php
if (!is_object($incomplete_obj)) {
echo 'This variable is not an object, it is a/an ' . gettype($incomplete_obj);
}
?>
Will print:
This variable is not an object, it is a/an object
