jimmywiddle
jimmywiddle

Reputation: 63

Small issue with custom code to detect if a user is a member of a specific usergroup

I have the following code which detects if a user is a member of a certain Joomla usergroup and displays the relevant link to the user.

This works great for 1 usergroup, BUT when a user is a member of more than 1 usergroup, the buttons are repeated for the amount of usergroups the user is a member of.

So if, for example, a user is a member of 4 usergroups, the button will be displayed 4 times (if the user is a member of the usergroup eg 'Usergroup001' 1 of the 4 buttons displayed will be a 'Start' button (as per the loop)).

Id like the buttons just to be displayed once, no matter how many usergroups the user is a member of.

<?php
$user_  = JFactory::getUser();
$db     = JFactory::getDBO();
foreach($user_->groups as $group){
$query  = 'SELECT title FROM #__usergroups';
$query .= ' WHERE id = ' . $group;
$db->setQuery( $query );
$grp = $db->loadResult();

if ($grp=='Usergroup001') : ?>
<a href="/start">Start</a>

<?php else : ?>
<a href="/sign-up">Sign up to Usergroup 001</a>

<?php endif; ?>
<?php
}
?>

Many thanks in advance if anyone can help!!!

Upvotes: 0

Views: 76

Answers (2)

mwweb
mwweb

Reputation: 7915

Try in_array

http://php.net/manual/en/function.in-array.php

if (in_array($grp,'Usergroup001')) : ?>
<a href="/start">Start</a>

<?php else : ?>
<a href="/sign-up">Sign up to Usergroup 001</a>

Upvotes: 0

Jaap Broeders
Jaap Broeders

Reputation: 66

Maybe this will work:

<?php 
$user_  = JFactory::getUser();
$db     = JFactory::getDBO();
$isMember = false;
foreach($user_->groups as $group){
    $query  = 'SELECT title FROM #__usergroups';
    $query .= ' WHERE id = ' . $group;
    $db->setQuery( $query );
    $grp = $db->loadResult();
    if ($grp=='Usergroup001') { 
        $isMember = true; 
        break; 
    }
}
if ($isMember ) : ?>
    <a href="/start">Start</a>
<?php else : ?>
    <a href="/sign-up">Sign up to Usergroup 001</a>
<?php endif; ?>

Upvotes: 1

Related Questions