Simple PHP Question: Conditional CSS class based on user

I am using this code to show a different styling class for the comment box if the comment is made by the Admin

<li class="<?php if ($comment->user_id == 1) $oddcomment = "authorstyle"; echo $oddcomment; ?>"></li>

The admin has the user_id = 1. Now, what if i want to add user_id 5 and 6, how would I edit this code?

Related posts

Leave a Reply

7 comments

  1. You could either use the || operator (which means or):

    if ($comment->user_id == 1 || $comment->user_id == 5 || $comment->user_id == 6)

    Or you could use in_array:

    if (in_array($comment->user_id, array(1, 5, 6))
    

    Which looks nicer and is more maintainable. 🙂

  2. One (possibly) robust way to handle this kind of situation is to ask if the userid is one of a set of userids, thus something fairly trivial as a condition is:

    in_array($comment->user_id, array(1,5,6))
    

    Clearly you’re developing some kind of permission system, so you’d really be better off coming up with a way to abstract user rights from their identities, and verifying a user has some privilege or status rather than in each place checking for said status.

    One way to do this might be assigning a user to an admin group, and then checking against the group, rather than against all ids. Better still, you could consider setting some number of properties on the group, say, has_style_xyz, then check against has_style_xyz in your conditional.

  3. You could use something like this:

    <li class="<?php
      if ($comment->user_id == 1)
         $oddcomment = "authorstyle";
      if ($comment->user_id == 2)
         $oddcomment = "somethingelse";
      if ($comment->user_id == 3)
         $oddcomment = "blahbalh";
     echo $oddcomment; ?>"></li>
    

    … and so on, for multiple styles.

    <li class="<?php
      if ($comment->user_id == 1 || $comment->user_id == 4 || $comment->user_id == 5)
         $oddcomment = "blahbalh";
     echo $oddcomment; ?>"></li>
    

    … for multiple IDs with one style.

  4. Simply use OR or || in your if statement.

    <li class="<?php if ($comment->user_id == 1 || $comment->user_id == 5 || $comment->user_id == 6) $oddcomment = "authorstyle"; echo $oddcomment; ?>"></li>

  5. You can try this code

    <?php 
    if ($comment->user_id == 1) 
       $oddcomment = "authorstyle"; 
    else($comment->user_id == 5)
        $oddcomment = "authorstyle2"; 
    else($comment->user_id == 6)
        $oddcomment = "authorstyle3"; 
    ?>
    
    <li class="<?php echo $oddcomment; ?>"></li>
    
  6. In a simple way you could do something like this:

         <?php
            $liStyles[1] = 'authorstyle';
            $liStyles[5] = 'somestyle';
            $liStyles[6] = 'someotherstyle';
         ?>
    
    
    
     <li class="<?php echo $liStyles[$comment->user_id]; ?>"></li>