【问题标题】:Using PHP trying to convert str to int使用 PHP 尝试将 str 转换为 int
【发布时间】:2011-12-09 00:28:31
【问题描述】:

我真的不明白为什么这不起作用,所以请帮忙。我正在尝试将 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" />

【问题讨论】:

  • 您是否收到错误消息?
  • 请正确描述哪些有效,哪些无效。输入是什么?预期和实际行为是什么?
  • 做一个 var_dump($_REQUEST['cost']);并查看内容。
  • 代码直接跳过if语句???
  • 这对我有用。不过,我不得不用表单标签包围输入标签。

标签: php string forms int


【解决方案1】:

我怀疑你需要:

if ($cost < 2) {
    exit(header('Location: page.php?say=numerror'));
}

【讨论】:

  • 哇!我从不使用 exit();它起作用了:)哇!我会记住这一点。现在我可以回去工作了。
  • 这不是你的实际错误。为您的脚本启用error_reporting(E_ALL);
  • @motto 这就是我想要弄清楚的。它只是不起作用,但是使用 exists() 它可以。我需要仔细检查其余部分以了解情况。变通办法不是一个好的解决方案。
  • 我想通了。我的 if 语句中断了,跳到了最后。我重新编写了整个 if 语句并将它们放在一起并且它起作用了。令人惊讶的是,exit() 是如何捕捉到它的。
  • 没有抛出错误。 header() 重定向不会停止代码的执行,因此它会继续执行。您必须放置 exit() 语句以停止执行继续(从而完成重定向)
【解决方案2】:

为什么你需要一个转换只是使用这个:

<?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" />

【讨论】:

    【解决方案3】:

    试试这个:

    <?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() PHP reference manual 的 intval() 函数的信息。我希望,这会有所帮助。

    如果这对您没有帮助。这是 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.S 函数从上面的链接复制。不是我的。

    【讨论】:

    • op 语句 ( $cost = (int)$cost; ) 足够好用了
    • 我当然不反对你,但是编写函数 str2int 的人是个傻瓜。他可以用正则表达式写一个单行函数来做同样的事情。
    • @FilipKrstic 我同意 Aurelio:这不是一个好的答案,str2int 甚至没有做 OP 想要的。
    猜你喜欢
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 2015-07-27
    相关资源
    最近更新 更多