bingjie2680
bingjie2680

Reputation: 7773

php if condition syntax error

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.

Upvotes: 1

Views: 535

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270617

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;

Upvotes: 4

linepogl
linepogl

Reputation: 9335

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.

Upvotes: 1

Related Questions