below there’s a code that I use very often on my website (it’s a MyBB forum) and there’s a specific web page where I have written it 10+ times.
To make code easier to read I decided to turn it into a function and call it with different arguments each time. Unfortunately it isn’t working, for some reason I keep getting the $fail code while without the function I get $success.
It’s the first time I use PHP functions but from what I read at w3schools I should be doing good, theoretically. Not much when coming to practice. Mind checking my syntax and tell me if it is wrong?
<?php //function code function canviewcheck($allowedgroups) { $groups = $mybb->user['usergroup']; if ($mybb->user['additionalgroups']) { $groups .= "," . $mybb->user['additionalgroups']; } $explodedgroups = explode(",", $groups); $canview = 0; foreach ($explodedgroups as $group) { if (in_array($group, $allowedgroups)) { $canview = 1; echo $success; break; } } if (!$canview) { echo $fail; } } //Parameters that I want to use $allowedgroups = [4, 19]; $pid = 'URL'; $success = "<a href=URL><span style='color:green; font-size:20px;'>SUCCESS</span></a>"; $fail = "<a href=" . $pid . "><span style='color:#DE1603; font-size:20px;'>FAIL</span>;</a>"; //Call to function canviewcheck($allowedgroups, $pid, $success, $fail);
Advertisement
Answer
You need to add all the necessary parameters to the function, and $mybb
also needs to be passed as an argument.
$pid
isn’t used in the function, so you don’t need to pass that as an argument.
<?php //function code function canviewcheck($allowedgroups, $success, $fail, $mybb) { $groups = $mybb->user['usergroup']; if ($mybb->user['additionalgroups']) { $groups .= "," . $mybb->user['additionalgroups']; } $explodedgroups = explode(",", $groups); $canview = 0; foreach ($explodedgroups as $group) { if (in_array($group, $allowedgroups)) { $canview = 1; echo $success; break; } } if (!$canview) { echo $fail; } } //Parameters that I want to use $allowedgroups = [4, 19]; $pid = 'URL'; $success = "<a href=URL><span style='color:green; font-size:20px;'>SUCCESS</span></a>"; $fail = "<a href=" . $pid . "><span style='color:#DE1603; font-size:20px;'>FAIL</span>;</a>"; //Call to function canviewcheck($allowedgroups, $success, $fail, $mybb);