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,000 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.