PHP中是否有与Python的成员资格操作符等效的运算符?
运算符" in“和”not in“是否在PHP领域中使用?
有没有一种简单的方法,就像在Python中那样,用PHP重写这个例子?
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")
或
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中是否存在“成员资格运算符”。
发布于 2018-06-28 00:46:25
就是这样!我希望这会有所帮助。
<?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";
}
?>
发布于 2018-06-28 02:10:07
不,没有一个运算符和python中的in
运算符做同样的事情。
PHP有一个内置的函数来处理所有事情:正如其他人所建议的,您可以使用in_array
来检查元素是否存在于数组中。
如果您正在尝试确定字符串是否包含子字符串(例如,“pepperoni”中的“oni”),您可以使用strpos
、substr
、preg_match
等PHP函数。
发布于 2018-06-28 02:52:51
因为jsaigle已经said了,所以没有一个运算符可以像in
和not in
那样做同样的事情。
为了好玩,这里有一个模拟它的包装器(参见https://3v4l.org/ZfCBH):
<?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;
}
}
https://stackoverflow.com/questions/51067701
复制相似问题