Hi there,
this fastest solution I found to identify a variable type without using gettype function:
<?PHP
function typeof($var) {
if (is_object($var))
return "object";
if (is_resource($var))
return "resource";
return (($var === null) ? "null" :
(((bool)$var === $var) ? "bool" :
(((float)$var === $var) ? "float" :
(((int)$var === $var) ? "int" :
(((string)$var === $var) ? "string" :
"unknown"
)
)
)
)
);
}
?>
Maybe someone has a more elegant solution to check for object and resource types...
The complete script - including several identify- and timing functions follow:
#!/usr/bin/php
<?PHP
function typeof_trinary($var) {
if (is_object($var))
return "object";
if (is_resource($var))
return "resource";
return (($var === null) ? "null" :
(((bool)$var === $var) ? "bool" :
(((float)$var === $var) ? "float" :
(((int)$var === $var) ? "int" :
(((string)$var === $var) ? "string" :
"unknown"
)
)
)
)
);
}
function typeof_if_query($var) {
if (is_object($var))
return "object";
if (is_resource($var))
return "resource";
if ((bool)$var === $var)
return "bool";
if ((float)$var === $var)
return "float";
if ((int)$var === $var)
return "int";
if ((string)$var === $var)
return "string";
if (null === $var)
return "null";
return "unknown";
}
function typeof_gettype($var) {
return \gettype($var);
}
$var = 100;
echo "start@ " . \date("Y-m-d H:i:s") . "\n";
echo "\$var = $var - gettype(\$var) = " . gettype($var) . "\n\n";
$time = -\microtime(true);
echo "typeof_if_query(\$var) = " . typeof_if_query($var) . "\n";
$time += \microtime(true);
echo "duration: " . \sprintf("%0.10f",$time) . "\n\n";
$time = -\microtime(true);
echo "typeof_gettype(\$var) = " . typeof_gettype($var) . "\n";
$time += \microtime(true);
echo "duration: " . \sprintf("%0.10f",$time) . "\n\n";
$time = -\microtime(true);
echo "typeof_trinary(\$var) = " . typeof_trinary($var) . "\n";
$time += \microtime(true);
echo "duration: " . \sprintf("%0.10f",$time) . "\n\n";
?>
My console output - try the script several times!:
$ ./gettype.php
start@ 2015-01-10 01:10:37
$var = 100 - gettype($var) = integer
typeof_if_query($var) = int
duration: 0.0000500679
typeof_gettype($var) = integer
duration: 0.0000309944
typeof_trinary($var) = int
duration: 0.0000240803