dongshenyu4638 2013-03-05 08:32
浏览 251
已采纳

PHP两个感叹号“!!”运算符与preg_match? [重复]

This question already has an answer here:

Saw this online in one PHP snippet here.

/**
 * @param string $str subject of test for integerness
 * @return bool true if argument is an integer string
 */
function intStr($str) {
    return !!preg_match('/^\d+$/', $str);
}

Running this code snippet produces:

> var_dump( intStr("abc") );
bool(false)

> var_dump( intStr("123") );
bool(true)

Questions:

  1. Is the dual exclamation mark a a valid operator, or is it just the same as a "not-not", which negates itself?

  2. Also, why is this operator used in-conjunction with the preg_match function?

</div>
  • 写回答

3条回答 默认 最新

  • douchuitang0331 2013-03-05 08:44
    关注

    preg_match returns 0 or 1 (or false on error) and this intStr function is meant to return a boolean value. A single !$x first converts $x to boolean, then negates. !!$x just reverts this negation, so it is a shorter way to write (bool)$x.

    However, this saving of four characters results in loss of readability (and two unneccessary operations, but that's negligible), so it's not recommended.

    It's clever code, but there is a rule in programming: Don't be clever

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

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入