Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save harshvardhanmalpani/8dd0222e4821d0e495532abe9007fef1 to your computer and use it in GitHub Desktop.
Save harshvardhanmalpani/8dd0222e4821d0e495532abe9007fef1 to your computer and use it in GitHub Desktop.
PHP caveats – int/float type conversion
<?php
// important to focus on the values with "e" scientific notation
// interesting results for "0.1",-0, "1" and "042"
$arr = ["true", true, false, "false",
0, -0.0, 00, "-0", "+0", "-0.0", "+0.0", "0", "0w", "0.0t",
"0.1", 0.1, 1, "1",
1e4, "2e", 2e4, "2e4",
1337e0, "1e3", 1e1,
1.3, "1.4", "1t", "1.5n",
0x1A, '0x539',
042, "042", +42, -42, "+42", "-42"];
$ent = "&#";
$valid = $ent . "9989";
$invalid = $ent . "10060";
foreach ($arr as $k => $i) {
echo "Test Value " . ($k + 1) . ": (" . gettype($i) . ")" . $i . "<br>";
echo "Integer <b>converted</b> Value: " . (int)$i . "<br>"; // can use intval also
echo "Float <b>converted</b> Value: " . (float)$i . "<br>"; // can use floatval also
if (is_numeric($i) !== false)
echo "$valid Valid Integer as per <i>is_numeric</i><br>";
else
echo "$invalid Invalid Integer as per <i>is_numeric</i><br>";
if (is_float($i) !== false)
echo "$valid Valid Float as per <i>is_float</i><br>";
else echo "$invalid Invalid Float as per <i>is_float</i><br>";
if (filter_var($i, FILTER_VALIDATE_INT) === 0 || !filter_var($i, FILTER_VALIDATE_INT) === false) {
$yourInteger = intval($i);
echo "$valid Valid Integer as per filter validate<br>";
} else {
$yourInteger = false;
echo "$invalid Invalid Integer as per filter validate<br>";
}
if (filter_var($i, FILTER_VALIDATE_FLOAT) === 0 || !filter_var($i, FILTER_VALIDATE_FLOAT) === false) {
$yourFloat = floatval($i);
echo "$valid Valid Float as per filter validate<br>";
} else {
$yourFloat = false;
echo "$invalid Invalid Float as per filter validate<br>";
}
echo "----<br>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment