PHP PHP Arrays and Control Structures PHP Conditionals Switch Statements

Peter Buckwalter
PRO
Peter Buckwalter
Pro Student 6,846 Points

Cant see to get the switch to work. It seems to look correct to me, its wrong somehow. Can someone give me a pointer?

In the error message it says that it cant see the case for the default???

switch.php
<?php
//Available roles: admin, editor, author, subscriber
if (!isset($role)) {
    $role = 'subscriber';
}

//change to switch statement
switch ($role != 'admin') {
    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.";
        break;

}

?>

1 Answer

Patricia Hector
Patricia Hector
40,132 Points

Hi Peter:

The issue is on switch ($role != 'admin'). A switch statement is used to check in a couple or many options/cases which one is first true, and when you find it you do something with that result. BUT all the functionality of a switch rely on the variable/expression you declare inside switch(<something>). For this challenge, we need to change our result when the $role variable changes, so that should be our first concert and we will be generating the output depending on the value of $role. It should be something like this:

switch ($role) {
    case "admin": /*if $role is equal to "admin", this case is TRUE, execute; if not continue */
       echo "As an admin, you can add, edit, or delete any post.";
       break;
    case "editor": /*if $role is equal to "editor", this case is TRUE, execute; if not, continue*/
       echo "As an editor, you can add or edit any post, and delete your own posts.";
       break;
  case "author": /*if $role is equal to "author", this case is TRUE, execute; if not, continue*/
       echo "As an author, you can add, edit, or delete your own post.";
       break;
    default: /*if no cases were TRUE or no break statement was found, the default statement will be trigged */
        echo "You do not have access to this page. Please contact your administrator.";
        break;
}

I also want to tell you that your code would work for the first task if you change

switch ($role != 'admin') { /*$role not equal "admin"*/

TO

switch ($role == 'admin') {/*$role equal "admin"*/

because in that switch you will be checking when it's admin or it's not. But you are restricting yourself to just two possible cases(TRUE/FALSE), and that is not the objective of a switch statement.

Happy coding. Ciao.