R
R
Ratami Sato2016-02-09 16:44:10
PHP
Ratami Sato, 2016-02-09 16:44:10

3 else or 2 if?

In general, I have a header, it should contain info for an unregistered user, for a regular user and for an admin. Users have user_group- where 1 is admin, 5 is a regular user.
So I decided for not logged in and logged in

if(empty ($_SESSION['username']) or empty ($_SESSION['id'])){
echo'
<div id="header">

</div>
';
}else{
echo'
<div id="header">
<a href="/">главная</a>
</div>
';
}

It is necessary that the admin sees all this, and also his own elements, such as the control panel

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Mikhail Osher, 2016-02-09
@miraage

It is possible to take out still obtaining of group of the user.

switch (true):
    case ($_SESSION['user_group'] ?? null) === 1:
        // admin
        break;
    case ($_SESSION['user_group'] ?? null) === 5:
        // user
        break;
    default:
        // guest
        break;
endswitch;

K
kompi, 2016-02-09
@kompi

To avoid torment: wrap, for example, getting a group into a function or method, and then more concisely iterate through switch:

function getUserGroup() {
//..
}
switch(getUserGroup()) {
  case 'admin': 
    break;
  case 'user': 
    break;
  case 'guest':
  default: 
    break;
}

L
Lumore, 2016-02-09
@Lumore

<div id="header">
<?php
if(empty ($_SESSION['username'] or empty ($_SESSION['id'])){

}else{
echo'
<a href="/">главная</a>
';
} elseif($_SESSION['username']['is_admin'] == true) {
echo 'admin';
}
?>
</div>

S
Silm, 2016-02-09
@Silm

1. We get the user group not from the session, but from the database
2. Display the required html block as you like, but not through nested if

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question