douguaidian8021 2013-11-30 02:09 采纳率: 100%
浏览 39
已采纳

php字符串到整数转换和比较

I'm somewhat confused and was hoping you guys could help. I'm writing something simple that takes a value from the posted name field and returns it, checking to see beforehand that its a string(correct) or an integer(in which case it'll say 'a name is not a number').

<?php

$number = array("1","2","3","4","5","6","7","8","9","0");

if(!isset($_POST['submit'])){
?>
<p>Enter your name</p>
<form method="post" action="action4.php">
    <input type="text" name="name">
    <input type="submit" name="submit">
</form>
<?php
}else{
$name = $_POST['name'];
foreach($number as $v){
$int = (int)$v;
}
if($name == $int){
    print "This is a number and not a name.";
}else{
            print $name;
   }
}
?>

Given that every number entered into the name field was seen as a string, I cycled through the array and converted every digit to an integer. When entering an integer into the name field however, rather than getting "this is a number and not a name" I get $name. Reciprocally if I enter in a string, I get "this is a number and not a name."

var_dumping both name and int in the if statement returns as expected: $name as string and $int as integer. So why are they comparing as true?

  • 写回答

2条回答 默认 最新

  • dsklfsdlkf1232 2013-11-30 02:12
    关注

    Because you are doing nothing but assigning a variable in your foreach loop the final value of $v is 0. When PHP compares strings to integers it converts the string to an integer to do the comparison (see Type Juggling). So $name becomes 0. 0 equals 0 so your if statement is always true.

    To overcome this you need to compare variable type and value (and do your comparison inside your foreach loop). This means using the === comparison operator which compares both type and value as opposed to just value which is what == does.

    Reference: Comparison operators, Type juggling

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)