note 73650 deleted from function.gettype by cmb

From: Date: Mon, 02 Nov 2020 21:52:50 +0000
Subject: note 73650 deleted from function.gettype by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-215772@lists.php.net to get a copy of this message
Note Submitter: sneskid at hotmail dot com ---- 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 ?>

« previous php.notes (#215772) next »