We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 31088
    • 14 Posts
    hi

    so, the following snippet works, but i am wondering if there’s a mo’ betta way to do it - specifically, if a condition is not met i have it just saying, " ". For some reason that bugs me, i can’t help but feel like i’m doing something bad...

    also, am i being paranoid with testing for the existence of a local file? i would if this was just a bit of procedural laziness in a normal web page, but i would love to know if it’s needed in modx.

    without further ado, here is the snippet - made to quickly add a js file to the head, for one of my designer clients to use:
    <?php
    $file = !empty($file) ? file_exists($file) : '' ? $modx->regClientStartupScript($file) : '';
      • 28042 ☆ A M B ☆
      • 24,524 Posts
      While the tertiary operator is a great favorite of mine, I usually prefer to be a bit less clever with my code in exchange for easier understanding of what it’s supposed to do. How about
      if(file_exists($file) && !empty($file)) $modx->regClientStartupScript($file);
      
        Studying MODX in the desert - http://sottwell.com
        Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
        Join the Slack Community - http://modx.org
        • 31088
        • 14 Posts
        embarrassed
        heheh ADHD plus weak coding skills.
        You are right. I had it sending messages before, and took that out. For some reason I didn’t spot not needing the "cleverness" (that’s a kind way of saying it, my frend!)

        Well, I guess this voids my question, pretty much! Thanks grin
          • 28042 ☆ A M B ☆
          • 24,524 Posts
          With nested tertiary operators, you need to be careful to keep the nesting in proper order (much like nesting HTML tags). The original operator does not close until the second one closes, which does not close until the third one closes.

          I like the example given on one site (bad URL, took some fiddling AdBlocker to block his logging functionality as the logging server was not responding)http://www.johnhok.com/2008/02/23/php-tip-tertiary-operator/
          (($query_count_result['count'] > 0) ? (($query_count_result['count'] == 1) ? $query_count_result['count'].' Song' : $query_count_result['count'].' Songs') : 'No Songs')

          This first check if there are any songs, if TRUE then with the nested operation it outputs "Song" if there is one song, and "Songs" if not 1 (there must be more than one at this point), then if the first check is FALSE it outputs "No Songs".
            Studying MODX in the desert - http://sottwell.com
            Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
            Join the Slack Community - http://modx.org