0

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!!!

2 Answers2

1

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; ?>
  • Have done, thanks again! I was wondering as I need to run this code several time in one page, im thinking it will be excessive on resources to run the db query each time, im trying to cut the query out and but no luck so far, once again any help would be much appreciated! :) Thanks again! – jimmywiddle Jan 20 '17 at 12:35
0

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>
mwweb
  • 7,625
  • 4
  • 19
  • 24
  • Hi, Many thanks for your reply/help, although unfortunetly the buttons are still display (the amount of times that a user is a member of a usergroup (if a user is a member of 4 usergroups buttons are displayed 4 times).. also your code does not provide the correct Start button if the user is a member of 'Usergroup001'. To clarify with your modified code all buttons are 'Sign up' regardless if the user is a member of the usergroup. Sorry for the bad news, and thanks so much for trying to help!!!!!!!!!!!!!!!!!!!!!!!! :) – jimmywiddle Jan 20 '17 at 08:45
  • @jimmywiddle try now – mwweb Jan 20 '17 at 08:55
  • Hi, Yes I did spot the missing closing bracket and added it, but im sorry to say im afraid it didn't work, once again many thanks for your time and help though!!! – jimmywiddle Jan 20 '17 at 12:36