I'm learning PHP and CakePHP and I have a problem with the following code. When I execute it (with WAMP: PHP 5.3.0, Apache 2.2.11 and MySql 5.1.36) appears a parse error in the line of endforeach. Somebody knows what is happend? All the documentation I read it says that the endforeach; is legal but... I have a problem :-(

Thanks in advance and have a nice day! Oscar.

<?php foreach($tasks as $task): ?>
<tr>
    <td><?php echo $task['Task']['title']; ?></td>
    <td>
        <?php if($task['Task']['done']): echo "Done";
              else: echo "Pending"; 
        ?>
    </td>
    <td><?php echo $task['Task']['created']; ?></td>
    <td><?php echo $task['Task']['modified']; ?></td>
    <td></td>
</tr>
<?php endforeach; ?>

Edited: added the colon after the foreach(..)

share|improve this question

feedback

4 Answers

up vote 0 down vote accepted

It is more clear if you strip the HTML:

<?php
foreach($tasks as $task):
    echo $task['Task']['title'];
    if($task['Task']['done']): echo "Done";
    else: echo "Pending"; 
    echo $task['Task']['created'];
    $task['Task']['modified'];
endforeach;
?>

As you can see you are missing the endif;:

<?php
foreach($tasks as $task):
    echo $task['Task']['title'];
    if($task['Task']['done']):
        echo "Done";
    else:
        echo "Pending"; 
    endif;
    echo $task['Task']['created'];
    $task['Task']['modified'];
endforeach;
?>
share|improve this answer
Thanks! The problem was because I missing the endif; as you say! – ocell Jul 22 '10 at 14:32
feedback

You forgot the endif; statement after line 6.

share|improve this answer
1  
+1: Good catch. As written, the endforeach is inside the else block, and is thus invalid. – Powerlord Jul 22 '10 at 14:14
feedback

Try to add ":" at the foreach statement:

<?php foreach($tasks as $task): ?>
share|improve this answer
feedback

The syntax is:

foreach($tasks as $task):
/* ... */
endforeach;

You're missing a : after foreach().

The error is at endforeach, because without the colon, it's equivalent to:

foreach($tasks as $task) {
/* one line here */
}

And then you use endforeach, outside of foreach -- so php doesn't throws the error here.

share|improve this answer
im always using foreach(...) { ... } – ahmet2106 Jul 22 '10 at 10:58
I try with the colon but error still: Parse error: parse error in index.ctp on line 25 (where the endforeach; is). – ocell Jul 22 '10 at 13:40
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.