dongmi6102 2015-10-26 15:34
浏览 97
已采纳

php从datetime对象比较01到1

DateTime object outputs 01, 02, 03 etc when I use

$num = $dt->format('d');

to get the day number

Then I compare the $num value if it's the first day of the month like so:

if ($num == 1)

but the $num value is '01'.

Now php compares it as expected

var_dump($num == 1)

returns true

I was thinking, should this be enough for me or I should enclose the $num variable with an intval like so:

intval($num)

this way if it is 01 it will display '1'

  • 写回答

2条回答 默认 最新

  • douweibiao8471 2015-10-26 17:43
    关注

    Basically $num = $dt->format('d') returns a String.

    If you have == as a Comparison Operators and the two values are not from the same data type, PHP try to match them.

    So in your case ($num == 1) you are comparing a String with a literal Integer

    Therefore PHP is trying to converting the Sting into a Integer (only for the comparison).
    In the end you are already comparing two Integers.

    The type conversion does not take place when the Comparison Operator is === or !== as this involves comparing the type as well as the value.

    So with $num = '1';, a comparison like $num === 1 would always return false.

    If you like to strip of leading zeros but don't convert the data type, I would use:
    $num_as_str = ltrim($num,'0');

    If you like to convert the variable to an Integer use this:
    $num_as_int = intval($num);

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

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP