note 73650 added to function.gettype
| From: | sneskid at hotmail dot com | Date: | Mon, 05 Mar 2007 21:56:56 +0000 |
| Subject: | note 73650 added to function.gettype | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-124124@lists.php.net to get a copy of this message | ||
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
?>
----
Server IP: 69.147.83.197
Probable Submitter: 74.118.123.241
----
Manual Page -- http://www.php.net/manual/en/function.gettype.php
Edit -- https://master.php.net/note/edit/73650
Del: integrated -- https://master.php.net/note/delete/73650/integrated
Del: useless -- https://master.php.net/note/delete/73650/useless
Del: bad code -- https://master.php.net/note/delete/73650/bad+code
Del: spam -- https://master.php.net/note/delete/73650/spam
Del: non-english -- https://master.php.net/note/delete/73650/non-english
Del: in docs -- https://master.php.net/note/delete/73650/in+docs
Del: other reasons-- https://master.php.net/note/delete/73650
Reject -- https://master.php.net/note/reject/73650
Search -- https://master.php.net/manage/user-notes.php