I understand that casting with (int)
rounds a number towards zero, but then I started poking around with bases other than 10 and now I'm not exactly sure what else (int)
does:
$a = 050; // an octal number
echo $a; // output is ----> 40
however
$a = '050';
echo (int)$a; // output is ----> 50
So I thought (int)
besides rounding towards zero also clips leading zeroes. But then if I do the same exercise as in the second code block (above) with binary I don't get what I expect:
$a = '0b010';
echo (int)$a; // output is ----> 0
and in hexadecimal:
$a = '0x050';
echo (int)$a; // output is ----> 0
Even using decimal scientific notation gives a quizzical result:
$a = 5e6;
$b = '5e6';
echo $a; // output is ----> 5000000
echo (int)$b; // output is ----> 5
What does casting to an integer using (int)
really mean? Besides stripping the decimal point and everything after in a float, does (int)
parse a cast string character-by-character, and return the concatenation of all leading, numeric, non-zero characters? Like this:
function intCast($str) {
$length = strlen($str);
$returnVal = '';
for($i = 0; $i < $length; $i++) {
// Note: ord() values 48 to 57 represent 0 through 9
if ($returnVal === '' && ord($str[$i]) == 48) {
continue; // leading zeroes are OK but don't concatenate
} else if (ord($str[$i]) > 48 && ord($str[$i]) < 58) {
$returnVal .= $str[$i];
} else {
break;
}
}
return (strlen($returnVal) > 0) ? $returnVal : 0;
}
***Note that this link does not seem to provide a sufficient answer.