adding or removing endforeach; throws error!

If you pasted your code directly,

The second curly bracket here <?php if($k==0) { ?> active <?php { ?> should be a closing one, like this:

<?php if($k==0) { ?> active <?php } ?>

There is also a stray slash </a>/</li> – should be – </a></li> – but that shouldn’t cause any PHP errors.