PHP PHP Arrays and Control Structures PHP Conditionals Switch Statements

I need help with challenge task 1 of 2 in the php arrays and controls structures

Switch Statements

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

//change to switch statement
switch ($role != 'admin') {
    default:
    echo "You do not have access to this page. Please contact your administrator.";
    break;



      case 'admin':
      echo " As an admin, you can add, edit, or delete any post";
      break;
}

2 Answers

John Lack-Wilson
John Lack-Wilson
8,161 Points

The issue here is that the switch statement takes a single expression expression n, for example switch (n), where n is generally a single variable.

With switch statements we use case to compare values.

Here's a very simple example to try and help you with completing the challenge:

$n = "5";

switch ($n) {
    case "1":
        echo "Not the right number";
        break;
    default:
        echo "Correct";
        break;
}
Robbie Thomas
Robbie Thomas
31,092 Points

This is what I got and it and gave me the green light.

$role != 'admin';

switch ($role) {
  default:
    echo "You do not have access to this page. Please contact your administrator.";
    break;

  case 'admin':
    echo "As an admin, you can add, edit, or delete any post.";
    break;
}

John Lack-Wilson pretty much has it right. All you need to add is $role != 'admin'; on top.

John Lack-Wilson
John Lack-Wilson
8,161 Points

In fact the $role != 'admin'; statement is redundant here, because $role is set to 'subscriber', and it is not necessary to say that 'subscriber' != 'admin'.

Robbie Thomas
Robbie Thomas
31,092 Points

Strange, sounds like you know more than me about this. I just did the code that way and TreeHouse gave me the thumbs up.