首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PHP中等同于Python的成员资格运算符

PHP中等同于Python的成员资格运算符
EN

Stack Overflow用户
提问于 2018-06-28 00:39:09
回答 4查看 417关注 0票数 -3

PHP中是否有与Python的成员资格操作符等效的运算符?

运算符" in“和”not in“是否在PHP领域中使用?

有没有一种简单的方法,就像在Python中那样,用PHP重写这个例子?

代码语言:javascript
复制
ingredients = ['cheese', 'tomato', 'onion', 'pepperoni']
if 'oni' in ingredients:
   print("The letters 'oni' is available in the given ingredients")
else:
   print("The letters 'oni' is NOT available in the given ingredients")

代码语言:javascript
复制
if 'oni' in 'pepperoni':
    print("The letters 'oni' is available in the given ingredient")
else: 
    print ("The letters 'oni' is NOT available in the given ingredient")

我已经知道在PHP中有数百万种方法可以获得相同的结果,但关键是PHP中是否存在“成员资格运算符”。

EN

回答 4

Stack Overflow用户

发布于 2018-06-28 00:46:25

就是这样!我希望这会有所帮助。

代码语言:javascript
复制
<?php
$ingridients = array("Cheese", "Tomato", "Onion", "Pepperoni");

if (in_array("oni", $ingridients))
  {
  echo "The letters 'oni' is available in the given ingredients";
  }
 else
   {
   echo "The letters 'oni' is NOT available in the given ingredients";
  }
?>
票数 1
EN

Stack Overflow用户

发布于 2018-06-28 02:10:07

不,没有一个运算符和python中的in运算符做同样的事情。

PHP有一个内置的函数来处理所有事情:正如其他人所建议的,您可以使用in_array来检查元素是否存在于数组中。

如果您正在尝试确定字符串是否包含子字符串(例如,“pepperoni”中的“oni”),您可以使用strpossubstrpreg_match等PHP函数。

票数 1
EN

Stack Overflow用户

发布于 2018-06-28 02:52:51

因为jsaigle已经said了,所以没有一个运算符可以像innot in那样做同样的事情。

为了好玩,这里有一个模拟它的包装器(参见https://3v4l.org/ZfCBH):

代码语言:javascript
复制
<?php

if (Term::create('oni')->in(['cheese', 'tomato', 'onion', 'pepperoni'])) {
    echo '"oni" is available in the given ingredients'.PHP_EOL;
} else {
    echo '"oni" is NOT available in the given ingredients'.PHP_EOL;
}

if (Term::create('oni')->in('pepperoni')) {
    echo '"oni" is available in the given ingredient'.PHP_EOL;
} else {
    echo '"oni" is NOT available in the given ingredient'.PHP_EOL;
}

// Pretend the following isn't here

class Term
{
    public $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public static function create($value)
    {
        return new self($value);
    }

    public function in($search)
    {
        return array_reduce((array) $search, function ($carry, $item) {
            return $carry ?: (bool) mb_substr_count($item, $this->value);
        });
    }

    public function notIn($search)
    {
        return !$this->in($array);
    }

    public function __toString()
    {
        return $this->value;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51067701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档