note 91732 added to language.types.type-juggling
| From: | Paul at osu1 dot php dot net | Date: | Wed, 24 Jun 2009 10:24:32 +0000 |
| Subject: | note 91732 added to language.types.type-juggling | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-157338@lists.php.net to get a copy of this message | ||
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
----
Server IP: 211.43.210.124
Probable Submitter: 92.65.202.83
----
Manual Page -- http://www.php.net/manual/en/language.types.type-juggling.php
Edit -- https://master.php.net/note/edit/91732
Del: integrated -- https://master.php.net/note/delete/91732/integrated
Del: useless -- https://master.php.net/note/delete/91732/useless
Del: bad code -- https://master.php.net/note/delete/91732/bad+code
Del: spam -- https://master.php.net/note/delete/91732/spam
Del: non-english -- https://master.php.net/note/delete/91732/non-english
Del: in docs -- https://master.php.net/note/delete/91732/in+docs
Del: other reasons-- https://master.php.net/note/delete/91732
Reject -- https://master.php.net/note/reject/91732
Search -- https://master.php.net/manage/user-notes.php