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 trial

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,181 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,093 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,181 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,093 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.