Reputation: 415
I'm attempting to learn how to work with PHP switch statements. What I would like to do is check on a users role id.
Am I forming this right and can I just break for the case 2 since I don't want them to do anything for an editor.
switch ($user_data->role_id)
{
// User
case 1:
$user_data->characters = $this->character->get_many_by('user_id', $user_id);
break;
// Editor
case 2:
break;
// Admins
case 3:
$user_data->characters = $this->character->get_many_by('user_id', $user_id);
break;
// Webmaster
case 4:
$user_data->characters = $this->character->get_all();
break;
}
Upvotes: 0
Views: 169
Reputation: 1651
I like Class' answer most. However, this is a typical case where your switch is allowed to take up some more space for clarity. You have defined user roles, and although users and admins may have things in common, they may not in the future. Case 2 is not useful now, but probably will be later on.
I'd add the default: break too for completeness. My answer:
switch ($user_data->role_id) {
case 1: // User
$user_data->characters = $this->character->get_many_by('user_id', $user_id);
break;
case 2: // Editor
break;
case 3: // Admin
$user_data->characters = $this->character->get_many_by('user_id', $user_id);
break;
case 4: // Webmaster
$user_data->characters = $this->character->get_all();
break;
default:
break;
}
Upvotes: 1
Reputation: 9270
If you don't want anything to happen if $user_data->role_id
is 2
(Editor), then you can just take out your case 2: break;
code.
Otherwise, your switch
statement looks fine to me!
EDIT: I probably should have looked at the question more closely; as Class said, you can combine your User and Admin cases. You do this by saying
case 1: case 3:
$user_data->characters = $this->character->get_many_by('user_id', $user_id);
break;
Upvotes: 1
Reputation: 1129
It seems good to me. For case 2 you should do it with the default!
switch ($user_data->role_id)
{
// User
case 1:
$user_data->characters = $this->character->get_many_by('user_id', $user_id);
break;
// Admins
case 3:
$user_data->characters = $this->character->get_many_by('user_id', $user_id);
break;
// Webmaster
case 4:
$user_data->characters = $this->character->get_all();
break;
default:
break;
//Editor and all the other non specifed
}
So the default is for all the cases you didn't mentioned before.
Upvotes: 1
Reputation: 3160
You could remove case 2 and combine 1 & 3 since they are the same and add a default to break
switch ($user_data->role_id){
// User
case 1:
// Admins
case 3:
$user_data->characters = $this->character->get_many_by('user_id', $user_id);
break;
// Webmaster
case 4:
$user_data->characters = $this->character->get_all();
break;
default:
break;
}
Upvotes: 3