2

i have the variable $uid that always contain a number. I want to execute different actions depending on how the $uid ends. For example:

if(&uid ENDS WITH 2,3 or 4) {echo "Some content"};
else if($uid ENDS WITH 1,5 or 6) {echo "Some other content"};
else if($uid ENDS WITH 7,8,9 or 0) {echo "Some other content"};

Nothing comes on my mind how to achieve this. Thanks in advance for Your time!

mr.d
  • 386
  • 4
  • 18

3 Answers3

3
$end = substr($uid, -1);
if($end == 2 || $end == 3 || $end == 4){
echo "Some content";
}
else if($end == 1 || $end == 5 || $end == 6){
echo "Some other content";
}
else if($end == 7 || $end == 8 || $end == 9 || $end == 0){
echo "Some other content";
}

Update: If you know that $uid is an integer, you may change the first line to:
$end = $uid % 10;

3

There are a few ways to swing this cat. Using lots of if/elseif like you have, but that becomes hard to read. You can use in_array() which is a good solution, but again you have several if/elseifs.

I prefer to use a switch.

$end=substr($uid, -1);

switch ($end){
    case 2:
    case 3:
    case 4:
        echo "Some content";
        break;
    case 1:
    case 5:
    case 6:
        echo "Some other content";
        break;
    case 7:
    case 8:
    case 9:
    case 0:
        echo "Some other other content";
        break;
}
Popnoodles
  • 28,090
  • 2
  • 45
  • 53
2

Try this:

    $endsWith = substr($uid, -1);
    if (in_array($endsWith, array(2, 3, 4)) echo "something";
    elseif () // ... etc
dan
  • 136
  • 8
  • I tried: `` and it outputs error: `syntax error, unexpected T_ECHO in /var/www/dn/index.php on line 4` any suggestions? – mr.d Dec 24 '13 at 16:28