【问题标题】:If condition wrongly working如果条件错误地工作
【发布时间】:2017-07-04 20:25:25
【问题描述】:

以下 PHP if 条件语句处理错误且不起作用。
文件 $fname 具有文本值:“990,1000”,中间有逗号:

$myfile = fopen($fname, "r") or die("<script 
type='text/javascript'>window.location.href = 
'http://www.autorekrooter.com/activation.html';</script>");
$dt=fread($myfile,filesize($fname));
//File fname has values: "990, 1000"
fclose($myfile);
$myArray = explode(',', $dt);
//Now checking if Limit expired or not?  
echo "<br>myArray[0] values is: " . $myArray[0] . " myArray[1] value is: " . 
$myArray[1];
if ($myArray[0]>=$myArray[1]){
echo "<script>alert('You can't proceed further');</script>";    
//echo "<script type='text/javascript'>window.location.href = 'register.html';</script>";
exit();
}
else{
echo "<script type='text/javascript'>window.location.href = 
'gui.php';</script>";
echo "You can proceed";
exit();
}

当我在 php 文件中运行上述内容时,if 语句始终将 myArray[0] &gt;= myArray[1] 的值视为 true 并显示 reigster.html 而在 $fname 文件中它是 990,1000 myArray[0]=990myArray[1]=1000 所以 myArray[0] 不应该大于 myArray[1] 并且 else 语句应该运行,但相反的情况正在发生。

关于为什么这不起作用的任何建议?
非常感谢您的回答。

【问题讨论】:

  • 你能告诉我们$dt的内容吗
  • $dt="990,1000" 它从文件中读取。在 cmets @Grumpy 中给出
  • 将 $myArray[0] 和 $myArray[1] 转换为 int 然后检查 $firstval= (int) $myArray[0]; $secondval= (int) $myArray[1] 并比较 $firstval 和 $secondval

标签: php if-statement


【解决方案1】:

您的文件末尾可能有一个换行符(\n\r\n)($myfile)。所以myArray[1] 实际上看起来像"1000\n"

var_dump("990" &gt;= "1000\n"); 返回bool(true)

您正在比较 PHP 无法转换为数字的字符串,因此您得到了意想不到的结果。

【讨论】:

  • PHP 脚本的输出:DT 变量中的值:990,1000
  • 如何在行尾删除 \r\n?任何建议.. @timclutton
  • 只需在第二个值后面加上 , 这样内容就变成了 990,1000,
  • @PuneetMathur 您需要比仅使用echo 更彻底地调试它。至少使用var_dump($myArray); 来检查这些值。 请记住,在网络浏览器中查看结果会删除空格!
【解决方案2】:

试试这个

$myArray = array_map('intval', explode(',', $dt));

【讨论】:

    【解决方案3】:

    您可以使用 intval 仅获取整数值。
    试试这个

    if (intval($myArray[0])>=intval($myArray[1])){
         echo "<script>alert('You can't proceed further');</script>";    
    //echo "<script type='text/javascript'>window.location.href = 'register.html';</script>";
    exit();
    }
    else{
    echo "<script type='text/javascript'>window.location.href = 
    'gui.php';</script>";
    echo "You can proceed";
    exit();
    }
    

    我觉得它对你有用。

    【讨论】:

      【解决方案4】:

      尝试: f ((int)$myArray[0]&gt;=(int)$myArray[1]){

      【讨论】:

      • 是的,您的类型转换代码对我有用。我会接受这个作为答案,请投票。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      相关资源
      最近更新 更多