Search code examples
phparraysrole

How to assign a role to a user PHP


Well I have this form that adds user, admin.I've given to user the right to add another user but not add an admin or so!

$roles = db_fetch_all("role") ; 
$TabRoles = array(''=>'-- Choose --');
foreach($roles as $value)
{
    $TabRoles[$value['rid']] = $value['name'];
} 

and with print_array($TabRoles); it displays me :

Array
(
    [] => -- Choose --
    [admin] => Admin
    [seo] => SEO
    [user] => User
)

The condistion is if (user('rid') == 'admin'|'seo') . I tried this :

foreach($roles as $value)
{
if (user('rid') == 'admin'|'seo')
    {
        $TabRoles[$value['rid']] = $value['name'];
    }else{

        $TabRoles[$value['rid']] = $value['name'][2];
    }
}

But it displays me the position "2" of the array !

Array
(
    [] => -- Choose --
    [admin] => m
    [seo] => O
    [user] => e
)

I want it to display like this :

Array
(
    [] => -- Choose --
    [user] => User
)

Any solution for this ? Many Thanks!

The solution : thanks to @DanFromGermany:

foreach($roles as $value)
{
if (user('rid') == 'admin' || user('rid') == 'seo')
    {
        $TabRoles[$value['rid']] = $value['name'];
    }elseif (user('rid') == $value['rid']){
 $TabRoles[$value['rid']] = $value['name'];
    }
}

Solution

  • if (user('rid') == 'admin'|'seo')
    

    | is a bitwise operator, but I guess you want a logical comparison here:

    if (user('rid') == 'admin' || user('rid') == 'seo')
    

    Explanation on using array brackets on strings:

    $test = 'abcd';
    
    echo $test[0]; // prints a
    echo $test[1]; // prints b
    echo $test[2]; // prints c
    

    That's why you get only a letter instead of the element you want.

    I think you are looking for something like:

    foreach($roles as $value) {
        if (user('rid') == $value['rid'])
            $TabRoles[$value['rid']] = $value['name'];
        }
    }
    

    or

    foreach($roles as $value) {
        $TabRoles[$value['rid']] = $value['name'];
    }
    
    if (user('rid') != 'seo' && user('rid') != 'admin')) { // inverse/negate the logic!
        unset($TabRoles['seo']);
        unset($TabRoles['admin']);
    }