如果我使用echo,三元运算符不工作

问题描述 投票:-3回答:2

我正在使用这个三元运算符:

$this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) !== false ? echo "Category containing categoryNeedle exists" : echo "Category does not exist.";

我也尝试过这样:

($this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) !== false) ? echo "Category containing categoryNeedle exists" : echo "Category does not exist.";

但我的IDE说unexpected echo after ?

php ternary-operator
2个回答
1
投票

你应该在PHP中阅读the differenceprint之间的echo。 Tl; dr使用print代替。

$this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) ?
    print "Category containing category needle exists" : 
    print "Category does not exist.";

但最好还是:

echo $this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) ?
    'Category containing category needle exists' : 
    'Category does not exist.';

3
投票

关于什么

echo(
    $this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) !== false
        ? "Category containing categoryNeedle exists"
        : "Category does not exist."
);
© www.soinside.com 2019 - 2024. All rights reserved.