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

Edward Lee
Edward Lee
1,805 Points

What's the purpose of the first condition here?

The first IF statement was pre-written but it was never explained what it does nor what the isset() does. Also, why couldn't we just assign a variable for $role to replace the whole condition?

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

//change to switch statement
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.";
    break;
}
?>
Daniel Bell
Daniel Bell
17,178 Points

In this example that if statement could have just been replaced with an assignment, you're right.

What isset() does is return true if a variable has been set, and false if it has not. A variable that has been set to "" or 0 is still set. You can look this up in the PHP documentation for a better explanation, you will see this function alot.

I don't know why they've used this condition here, but it looks like it's allowing you to add code later that sets $role based on some previous action like logging in. The isset() conditional sets it to 'subscriber' by default, effectively, if nothing else has been assigned to that variable beforehand.

1 Answer

the condition statement, is to test if $role variable is not set and if it is not set,then initialise $role to value ''subscriber'',so that, the switch statement, will execute default statement i.e "You do not have access to this page. Please contact your administrator.";..I hope i answered you clearly.