I have the following code:
<?php
function s2int($pinned_id) {
$action="aaa";
if ( $action && is_numeric($pinned_id) && (float)$pinned_id==(int)$pinned_id) {
/**
* @param [string] $action is setted
* @param [int/string as int] $pinned_id is setted
*/
echo "-chekpoint- $pinned_id
";
$pinned_id = (int)$pinned_id;
}
else { echo "-passpoint- $pinned_id
";}
return $pinned_id;
}
echo s2int("000010")."
";
echo s2int(10.00001)."
";
echo s2int(10)."
";
echo s2int("10")."
";
echo s2int("0")."
";
echo s2int("a")."
";
echo s2int("a10")."
";
echo s2int("10a")."
";
echo s2int("0x1A")."
";
echo s2int("-100")."
";
OUTPUT:
-chekpoint- 000010
10
-passpoint- 10.00001
10.00001
-chekpoint- 10
10
-chekpoint- 10
10
-chekpoint- 0
0
-passpoint- a
a
-passpoint- a10
a10
-passpoint- 10a
10a
-chekpoint- 0x1A
0
-chekpoint- -100
-100
EXPECTED OUTPUT:
-chekpoint- 000010
10
-passpoint- 10.00001
10.00001
-chekpoint- 10
10
-chekpoint- 10
10
-chekpoint- 0
0
-passpoint- a
a
-passpoint- a10
a10
-passpoint- 10a
10a
-passpoint- 0x1A
0x1A
-chekpoint- -100
-100
what is best practice to make s2int to return correct (int) variable and make action if variable can't be converted to (int) (as you see result unexpected if input is hexadecimal ?
I would use filter_var()
for that:
if (false === ($x = filter_var($pinned_id, FILTER_VALIDATE_INT))) {
echo "Could not convert $pinned_id to an integer";
}
// $x is an integer
The case of 000010
was ambiguous, as it could mean octal as well; but if you want a 10-base number, you have to strip any leading zeroes:
$num = preg_replace('/^0+(\d+)/', '\\1', $pinned_id);
if (false === ($x = filter_var($num, FILTER_VALIDATE_INT))) {
echo "Could not convert $pinned_id to an integer";
}
// $x is an integer
If you also want to allow hexadecimal:
if (false === ($x = filter_var($num, FILTER_VALIDATE_INT, array(
'flags' => FILTER_FLAG_ALLOW_HEX,
))) {
echo "Could not convert $pinned_id to an integer";
}
// $x is an integer
Edit
You could also go for the preg_match()
route:
function s2int($pinned_id) {
echo "/$pinned_id/ ";
if (!preg_match('/^-?\d+$/', $pinned_id)) {
echo "Could not convert $pinned_id to an integer";
return false;
}
return (int)$pinned_id;
}
This won't run on codepad for some reason, but it should run on any other system
function s2int($pinned_id) {
// use regex (regular expression)
$pattern = "/[a-zA-Z.]/";
$bool = preg_match($pattern, $pinned_id);
// check if $pinned_id is without any character in the $pattern
if ( $bool == false ) {
/**
* @param [string] $action is setted
* @param [int/string as int] $pinned_id is setted
*/
echo "-chekpoint- $pinned_id<br />";
$pinned_id = (int)$pinned_id;
} else {
echo "-passpoint- $pinned_id<br />";
}
return $pinned_id;
}