简体   繁体   中英

Ternary operator not working if I am using echo

I am using this ternary operator:

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

I also tried it like this:

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

But my IDE says unexpected echo after ?

What about

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

You should read about the difference between print and echo in PHP in general. Tl;dr use print instead.

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

But it's better to just:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM