Burim Hiseni
Burim Hiseni

Reputation: 3

User role with if statement inside array (PHP)

I have been stuck here for 2 days, the problem is user role, the script I used has 3 user roles, (user, moderator, admin)"numeric" , with the current configuration, user role(USER) and admin role(Admin) works very well, but that of moderator is impossible to fix it. thanks for your help. here is the script

<?php if (empty($wo['user'])) {
    header("Location: " . Wo_SeoLink('index.php?link1=welcome'));
    exit();
}
$webmasterid = YOUR_WEBMASTERID;
$password = 'YOUR_SCRIPT_CHAT_PASSWORD';
$user = array(
    'username'=>$wo['user']['username'],
    'image'=>base64_encode($wo['user']['avatar']),
    'gender'=>$wo['user']['gender'],
    'role'=>($wo['user']['admin']==1)?'admin':'user', 
/* user role admin is =1,user role moderator is =2, and user role USER is =0
can i input here the if statement!!? if YES, HOW!! */
    'password'=>$password
);
$encrypted = file_get_contents("https://html5-chat.com/protect/".base64_encode(json_encode($user)));
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat</title>
</head>
<body>
    <script src="https://html5-chat.com/script/<?=$webmasterid?>/<?=$encrypted?>"></script>
</body>
</html>
<?php exit();?>

Upvotes: 0

Views: 1049

Answers (1)

M. Eriksson
M. Eriksson

Reputation: 13635

You can't put if inside array definitions. You could use nested ternaries (like: $foo == 1 ? 'admin' : ($foo == 2 ? 'moderator' : 'user') but these tend to be hard to read and easy to mess up so it's highly discouraged.

Alternative 1

You can set a $role variable before the array definition:

$role = 'user';
if ($wo['user']['admin'] == 1) {
    $role = 'admin';
} else if ($wo['user']['admin'] == 2) {
    $role = 'moderator';
}

// Now just use the $role variable
$user = array(
    ...
    'role' => $role, 
    ...

Alternative 2

Same as alternative 1, but with switch/case:

switch($wo['user']['admin']) {
    case 1:
        $role = 'admin';
        break;
    case 2:
        $role = 'moderator';
        break;
    default: 
        // Having this as default protects us from strangeness
        // if we would get something other than 0-2
        $role = 'user';
        break;
} 

// Now just use the $role variable
$user = array(
    ...
    'role' => $role, 
    ...

Alternative 3

Create an array with the different roles with the id as the key:

$roles = [
    'user',
    'admin',
    'moderator'
];

// Now you can fetch the role when defining the array by the id/key
$user = array(
    ...
    'role' => $roles[$wo['user']['admin']], 
    ...

Upvotes: 2

Related Questions