1

I have these code:

<?php 
$i=0;
while (true):
   echo "test";
   $i<4 ? $i++ : break;
endwhile; 
?>

error message: Parse error: syntax error, unexpected T_BREAK in C:\xampp\htdocs\data\index.php on line 5

there is a syntax error with the if condition, I can really make out what. can anybody help. thanks a lot.

1
  • 1
    This is what happens when people get told that ? : is "just like if-else" Commented Jan 15, 2012 at 19:03

2 Answers 2

4

The ternary operator is used for assignment or to return a value. You cannot place break in the else (:) case of a ternary operation.

// Assignment
$x = $i<4 ? $i : 0;
// For a value returned into a function argument $i or 0
do_something($i<4 ? $i : 0);

It cannot be used for a regular else case containing a language construct as you're doing with break. Instead use a regular if()

$i = 0;
while (true):
  if ($i<4) {
    $i++
  }
  else {
    break;
  }
endwhile;
Sign up to request clarification or add additional context in comments.

2 Comments

Hope you don't mind the edit, you had inconsistent bracing in the if else.
I think that it is not obligatory to use the returned value of the ternary expression. Therefore, it could be used as a standalone statement.
1

The syntax for the ternary operator is like that:

ternary_expression ::= boolean_expression ? expression : expression

The problem with your example is that break is not an expression but a statement. Your syntax could work if you had an expression instead, although it would seem awkward. I would suggest a normal if in any case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.