note 110795 deleted from function.is-int by googleguy

From: Date: Sun, 09 Dec 2012 08:31:42 +0000
Subject: note 110795 deleted from function.is-int by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192429@lists.php.net to get a copy of this message
Note Submitter: mitislumen at gmail dot com ---- This tiny function will do both, cast and verify any string to int or float: <?php function str_cast($s) { $v = 0 + $s; return "$v"==$s ? $v : $s; } //Test: var_dump(str_cast("5.3")); //float(5.3) var_dump(str_cast("5")); //int(5) var_dump(str_cast("0s")); //string(2) "0s" var_dump(str_cast("0xFF")); //int(255) var_dump(str_cast("3.5E6")); //float(3500000) var_dump(str_cast("34875374653874538746385746538764538746538746538746538645123472974652937846529876")); //string(80) "34875374653874538746385746538764538746538746538746538645123472974652937846529876" ?> You can use this trick to check for type: <?php function is_really_for_sure_float($s) { $v = 0 + $s; return ("$v"==$s && is_float($v)) ? true : false; } var_dump(is_really_for_sure_float('5')); //false var_dump(is_really_for_sure_float('5.2')); //true var_dump(is_really_for_sure_float('0xFF')); //false var_dump(is_really_for_sure_float('3.5E2'));//true ?>

« previous php.notes (#192429) next »