【问题标题】:PHP XOR - how to use with if( )?PHP XOR - 如何与 if() 一起使用?
【发布时间】:2012-02-26 16:34:51
【问题描述】:

我想知道如果不是

function edit_save($data, $post_id, $post_type)
{
    if (($post_type == 'A') OR ($post_type == 'B')) {

            // do this

    }

我可以像下面这样使用 XOR——但这不起作用...

function edit_save($data, $post_id, $post_type)
{
    if ($post_type == 'A' XOR 'B') { // pseudo code

            // do this

    }

有什么建议可以简化整体语法并在条件语句中呈现变量的 2 个潜在选项?

【问题讨论】:

  • 您只需在代码中将 X 添加到 OR。
  • 谢谢,但是有没有办法不重复变量,提供变量的两个选项?
  • 我不明白一个字符串怎么能同时等于'A' AND 'B'...
  • 为什么 PHP 不能读懂我的想法? -- :P -- 或者我的问题应该更清楚 -- 将编辑
  • @torr 不,因为'B' 本身会解析为TRUE。您必须每次都重复比较。

标签: php boolean xor


【解决方案1】:

试试:

function edit_save($data, $post_id, $post_type)
{
    if (($post_type == 'A') XOR ($post_type == 'B')) {

            // do this

    }

代码中的第二条语句 ('B') 将始终返回 true。您需要完整的条件语句才能使其工作。

【讨论】:

    【解决方案2】:

    看起来你想要的实际上是这样的:

    if (in_array($post_type,array('A','B'))) { 
       ...
    }
    

    在 PHP 5.4+ 中看起来会更好:

    if (in_array($post_type,['A','B'])) { 
       ...
    }
    

    【讨论】:

      【解决方案3】:

      嗯?

      function edit_save($data, $post_id, $post_type)
      {
          if (($post_type == 'A') XOR ($post_type == 'B')) {
      
                  // do this
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-06
        • 1970-01-01
        • 2012-09-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多