note 91732 deleted from language.types.type-juggling by danbrown

From: Date: Wed, 24 Jun 2009 13:32:34 +0000
Subject: note 91732 deleted from language.types.type-juggling by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-157357@lists.php.net to get a copy of this message
Note Submitter: Paul ---- Also casting an integer to a string only works if the integer is located at the beginning of the string. So I wouldn't rely on it for switch statements. Consider these examples: <?php $i = "In 911 more than a 1000 people died horrible"; $j = "911; more than a 1000 people died horrible"; $k = " 911; more than a 1000 people died horrible"; print (int)$i; // 0 - Less then ok print "\n"; print (int)$j; // 911 - Ok print "\n"; print (int)$k // 911 - spaces are ok ?> Better convert it yourself if you need to. With a simple regular expression you can do the same ('/\d+/'), only better: function toInt($string){ if(preg_match('/\d+/', $string, $matches)){ return (int)$matches[0]; } else { return 0; } } The only problem with this aproach is that it is 4 times slower than using a cast: <?php $time1 = benchmark('bench1'); $time2 = benchmark('bench2'); $timev = $time1/$time2; print "With pregmatch: $time1, With cast: $time2, $timev times slower \n"; function bench2(){ $i = "In 911 more than a 1000 people died horrible"; $j = "911; more than a 1000 people died horrible"; $k = " 911; more than a 1000 people died horrible"; print (int)$i; print "\n"; print (int)$j; print "\n"; print (int)$k; print "\n"; } function bench1(){ $i = "In 911 more than a 1000 people died horrible"; $j = "911; more than a 1000 people died horrible"; $k = " 911; more than a 1000 people died horrible"; print toInt($i); print "\n"; print toInt($j); print "\n"; print toInt($k); print "\n"; } function benchmark($function, $times = 10000){ $start = microtime(); ob_start(); for($p = 0; $p < $times; $p++){ $function(); } $end = microtime(); ob_end_clean(); return $end - $start; } function toInt($string){ if(preg_match('/\d+/', $string, $matches)){ return (int)$matches[0]; } else { return 0; } } ?> Results: With pregmatch: 0.148009, With cast: 0.044002, 3.36368801418 times slower

« previous php.notes (#157357) next »