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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度