我真的不明白为什么这个不工作,所以请帮助。我试图将一个str转换为int并使用它做if语句,但由于某种原因我不能。代码跳过if语句,就像它不存在一样??
<?php
$cost = $_REQUEST['cost'];
$cost = (int) $cost;
if($cost < 2){
header('Location: page.php?say=numerror');
}
?>
<input name="cost" id="cost" type="text" class="tfield" />
我怀疑你需要:
if ($cost < 2) {
exit(header('Location: page.php?say=numerror'));
}
为什么需要转换呢?
<?php
$cost = $_REQUEST['cost'];
if($cost < 2 or !is_numeric($cost)){
header('Location: page.php?say=numerror');
}
?>
<input name="cost" id="cost" type="text" class="tfield" />
试试这个:
<?php
$cost = $_REQUEST['cost'];
$cost = intval($cost);
if($cost < 2){
header('Location: page.php?say=numerror');
}
?>
// HTML
<input name="cost" id="cost" type="text" class="tfield" />
这里有更多关于intval()函数的信息,参见intval() PHP参考手册。我希望这对你有帮助。
如果这对你没有帮助。这是一个PHP函数,你可以从字符串中分离整数。
<?php
function str2int($string, $concat = true) {
$length = strlen($string);
for ($i = 0, $int = '', $concat_flag = true; $i < $length; $i++) {
if (is_numeric($string[$i]) && $concat_flag) {
$int .= $string[$i];
} elseif(!$concat && $concat_flag && strlen($int) > 0) {
$concat_flag = false;
}
}
return (int) $int;
}
// Callings
echo var_dump(str2int('sh12apen11')); // int(12)
echo var_dump(str2int('sh12apen11', false)); // int(1211)
echo var_dump(str2int('shap99en')); // int(99)
echo var_dump(intval('shap99en')); // int(0)
?>
p。从上面的链接复制的函数。不是我的。