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条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程