dswu26846 2018-11-12 07:02
浏览 44
已采纳

为什么PHP中的字符串等于整数0?

In php 7 I did this.The output should be 0 right?But I am getting a 1.Why is that?

 <?php
     echo "a"==0?1:0;
    ?>
  • 写回答

2条回答 默认 最新

  • duanjiaoxi4928 2018-11-12 07:05
    关注

    "a" == 0 evaluates to true.

    Because any string is converted into an integer when compared with an integer. If PHP can't properly convert the string then it is evaluated as 0. So 0 is equal to 0, which equates as true.

    If you want the answer as 0,

    you should use === instead of ==,

    Because the ordinary operator does not compare the types. Instead it will attempt to typecast the items.

    Meanwhile the === takes in consideration type of items.

    === means "equals",

    == means "eeeeh .. kinda looks like"

    Also, the PHP manual for comparison http://au.php.net/manual/en/language.operators.comparison.php

    // double equal will cast the values as needed followin quite complex rules
    0 == '0' // true, because PHP casted both sides to numbers
    
    // triple equals returns true only when type and value match
    0 === '0' // false
    

    FYI, From the PHP manual:

    String conversion to numbers

    When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

    The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.

    The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?