Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDan Boswell
2,570 PointsSwitch Statement Not Working
Why doesn't this code work in your tutorial?? I can't figure it out...
switch ($role) { default: echo "You do not have access to this page. Please contact your administrator."; case "admin": echo "As an admin, you can add, edit, or delete any post."; break; }
<?php
//Available roles: admin, editor, author, subscriber
if (!isset($role)) {
$role = 'subscriber';
}
//change to switch statement
switch ($role) {
default:
echo "You do not have access to this page. Please contact your administrator.";
case "admin":
echo "As an admin, you can add, edit, or delete any post.";
break;
}
2 Answers
Leandro Botella Penalva
17,618 PointsHi Dan,
You need to put a break at end of the default clause before the case "admin": line because if the role is not admin it will print the "You do not have access to this page. Please contact your administrator." message and also the "As an admin, you can add, edit, or delete any post.". That is how switches work. Once a switch enters one case or the default it will execute everything until the end of the switch or a break.
Other option would be putting the default at the bottom of the switch after all the cases, so in this case you would not need the break anymore as there is nothing else to execute after the default.
Dan Boswell
2,570 PointsHi Leandro,
Your solution worked perfectly! I think I tried this but probably had some syntax error on my part.
Anyway on I go!
Thanks!
Anders Prytz
26,193 PointsAnders Prytz
26,193 PointsI think your problem is that you do not break out of the default case, and will, in this case, print both echos in the switch when a default is triggered. I would also recommend to put the default case at the bottom of the switch statement, since this should "catch" everything not passing into the other cases. This would also work without the break statement in the default, since there are no more cases below. example: switch ($role) { case "admin": echo "As an admin, you can add, edit, or delete any post."; break; default: echo "You do not have access to this page. Please contact your administrator."; }