-1

I have a problem with an if statement

I want to display a different button for elements that are assigned to a specific category (7) than for elements that do not belong to that category:

<?php
            $result=get_media($ref);
            if(empty($result))

                include ('button1.php');

            if (count($result)>0)
            {

                for ($n = 0; $n < count($result); $n++)
                {

                    if($result[$n]["ref"] == '7')
                    {
                        include ('button2.php');
                    }
                    else 
                        include ('button1.php');
                }
            }
            ?>

The if statement works if the element is assigned to category "7" only. But if it is assigned to other categories as well, the "else" command is not working and both buttons are shown.

I could of course add more category IDs to the if statement but this would be a lot of them.

Also an unequal command in the else statement does not work.

p.dahl
  • 1
  • 1

1 Answers1

0

Since 7 is your only trigger, let's simplify things a bit.

<?php
            $result = get_media($ref);
            $button = 'button1.php';
            $count  = count($result);

            if ($count > 0) {
               for ($n = 0; $n < $count; $n++) {
                  if($result[$n]["ref"] == '7') {
                        $button = 'button2.php';
                   }
               }
            }
            include ($button);
            ?>

Or use an array function. Not sure which one is faster.

<?php
            $result = get_media($ref);
            $button = 'button1.php';
            $count  = count($result);

            if ($count > 0) {
                  if(in_array(7, array_column($result, 'ref'))) {
                        $button = 'button2.php';
                  }
            }
            include ($button);
            ?>
RST
  • 3,899
  • 2
  • 20
  • 33
  • I tried the first solution and it worked. It's perfect. If the second one is faster, how could I test it? I'd rate the answer as useful, but I still don't have enough reputation. Later, then. – p.dahl May 28 '20 at 16:12
  • take a look at the microtime function. Or this post https://stackoverflow.com/questions/1200214/how-can-i-measure-the-speed-of-code-written-in-php – RST May 28 '20 at 16:16