-2

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 ?

Black
  • 15,426
  • 32
  • 140
  • 232
  • Language? The ternary operator usually works for expressions than can be evaluated: `cond ? trueValue : falseVaue` as opposed to `cond ? doIfTrue : doIfFalse`. Does the echo function return something? – vc 74 Feb 28 '19 at 08:38
  • 2
    Then `echo` does not return anything, you can't use it like this but you can use `if else` instead – vc 74 Feb 28 '19 at 08:41

2 Answers2

3

What about

echo(
    $this->checkIfProductCategoriesContainsString($productId, $categoryNeedle) !== false
        ? "Category containing categoryNeedle exists"
        : "Category does not exist."
);
NullDev
  • 5,940
  • 4
  • 28
  • 47
1

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.';
emix
  • 14,448
  • 10
  • 62
  • 82