Python';PHP中的s成员操作符等价物
PHP中是否有Python成员操作符的等价物 PHP universe中是否使用了“in”和“not in”运算符 有没有一种直接的方法可以像Python那样用PHP重写这个例子Python';PHP中的s成员操作符等价物,php,python,Php,Python,PHP中是否有Python成员操作符的等价物 PHP universe中是否使用了“in”和“not in”运算符 有没有一种直接的方法可以像Python那样用PHP重写这个例子 ingredients = ['cheese', 'tomato', 'onion', 'pepperoni'] if 'oni' in ingredients: print("The letters 'oni' is available in the given ingredients") else: p
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")
或
我已经知道,在PHP中有数百万种方法可以获得相同的结果,但关键是PHP中是否存在“成员操作符”。好了!我希望这会有帮助
<?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";
}
?>
不,没有一个操作符可以做与python中的操作符相同的事情
PHP有一个内置函数,可以处理几乎所有的事情:正如其他人所建议的,您可以在数组中使用
来检查数组中是否存在元素
如果您试图确定字符串是否包含子字符串(例如“pepperoni”中的“oni”),则可以使用PHP函数,如strpos
、substr
、preg\u match
,等等。与Python中的和不在中一样,没有一个操作符可以执行与中的相同的操作
为了好玩,这里有一个包装器来模拟它(请参阅):
尽管大多数答案都不明白问题中写了什么,但有一个正确的答案,我可以得出结论
PHP中没有一个运算符或函数可以与Python中的“in NOT in”成员运算符执行相同的操作。是的,请参阅。。。虽然我不明白为什么你会想从一个了不起的人变成php,但我不明白Derson看一看@JoranBeasley也许是一些客户规范或公司规范,我确实很喜欢python,但到目前为止我使用了5种不同的语言,哈哈哈,我确实必须承认php in_数组函数与python成员操作符类似,但不同。在我的第一个示例中,PHP in_array是解决方案,第二种是PHP strps()。就是这样,在PHP中,有两个函数需要执行与Python成员资格运算符相同的操作。好的,现在,如果“pepperoni”中的“oni”,请在PHP中尝试此操作:print(“oni”字母在给定的成分中可用”)否则:print(“oni”字母在给定的成分中不可用”)抱歉,我不理解您的评论@Anderson。在PHP中尝试这个是什么意思?代码已经是PHP了。谢谢,你好,桑兹。PHP in_array适用于数组。但我现在给出的是,如果“辣味香肠”中的“oni”:print(“字母“oni”在给定的配料中可用”)或者:print(“字母“oni”在给定的配料中不可用”)只是一个字符串“辣味香肠”。在Python中,它会导致字母“oni”在给定的成分中可用,而在PHP中则不可用。您是唯一理解并回答我问题的人。你明白问题的重点了。
<?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";
}
?>
<?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;
}
}