We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 36686
    • 165 Posts
    Hi,

    I've created two snippets to show different content depending on how many images are in a MIGX table on a page. It works fine if there are one or more images, but if there are zero images it displays the same content as if there was one.

    Snippet #1 (for 1 image):

    <?php
    $items = $modx->fromJSON($input);
    if(count($items) == 1){
    $output = 'Output this if there is 1 image';
    };
    return $output;


    Snippet #2 (for 2 or more images):

    <?php
    $items = $modx->fromJSON($input);
    if(count($items) > 1){
       $output = 'Output this if there is 2 or more images';
    };
    return $output;


    So, snippet #2 works as expected, the content is only shown of there are two or more images.

    The content in snippet #1 on the other hand is shown even if there are 0 images, and I only want to to show if there is exactly one image.

    Any ideas of what I'm doing wrong? [ed. note: sketchi last edited this post 9 years, 7 months ago.]
      • 42562
      • 1,145 Posts
      Philosophical question for you:
      Is the glass really empty?

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

      <?php
      $items = array(""); // will count as 1, therefore true
      if (count($items) === 1) {
          echo "true";
      }
      
      $items = array("one"); // will count as 1, therefore true
      if (count($items) === 1) {
          echo "true";
      }
      ?>


      Solution, uproot all weeds, with array_filter
      <?php
      $output = "";
      $items = $modx->fromJSON($input);
      if(count(array_filter($items)) === 1){
         $output = 'Output this if there is 1 image';
      };
      return $output;
      </php>
        TinymceWrapper: Complete back/frontend content solution.
        Harden your MODX site by passwording your three main folders: core, manager, connectors and renaming your assets (thank me later!)
        5 ways to sniff / hack your own sites; even with renamed/hidden folders, burst them all up, to see how secure you are not.
        • 36686
        • 165 Posts
        donshakespeare, I don't understand a thing, but that's not what matters. What matter is that it works, and it does!

        Thank you so much, you're a poet AND a life saver wink
          • 42562
          • 1,145 Posts
          Glad you were able to move on from that error.
          Cheers
            TinymceWrapper: Complete back/frontend content solution.
            Harden your MODX site by passwording your three main folders: core, manager, connectors and renaming your assets (thank me later!)
            5 ways to sniff / hack your own sites; even with renamed/hidden folders, burst them all up, to see how secure you are not.