We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 13736
    • 345 Posts
    I was wondering if someone could explain to me what the ? and .= operators are for in PHP. Google searching for an explaination has proved futile.

    I was trying to mentaly step through the DropMenu snippet code to see if I could make a small change but I must not be understanding something correctly. I’m getting an error talking about some period and semicolon.

    Anyway.






      • 22303 MODX Staff
      • 10,725 Posts
      Quote from: jbjones at Jun 04, 2006, 10:59 PM

      I was wondering if someone could explain to me what the ? and .= operators are for in PHP. Google searching for an explaination has proved futile.

      I was trying to mentaly step through the DropMenu snippet code to see if I could make a small change but I must not be understanding something correctly. I’m getting an error talking about some period and semicolon.

      For ?, see PHP documentation on the ternary operator.

      For .=, this is simply a shorthand for assignment that includes the current value, i.e.

      <?php
      $foo= 'foo';
      $foo.= 'bar';
      ?>


      will produce the same result as

      <?php
      $foo= 'foo';
      $foo= $foo . 'bar';
      ?>


      See more on assignment operators.
        • 28042 ☆ A M B ☆
        • 24,524 Posts
        The terniary operator is great; as its name implies it takes three arguments. Like an "if" it takes an expression to evaluate to true or false; then comes the ?. If the first evaluation is true, the first expression after the ? is used. Then comes the : which is what is used if the first evaluation is false. So you can read it "Is this true? yes - do this : no - do this; ".

        Basically, it gets the same results as a simple if...else block. I think it’s faster and more efficient, though.

        $result = $something ? $this : $that;

        if($something) {
          $result = $this;
        } else {
          $result = $that;
        }


        We use the .= assignment operator a lot in snippets:
        // we got a list of stuff, maybe from the database, here's how to display it:
        $output = "<ul>"; // start the list
        foreach ($list as $item) {
        $output .= "<li>$item</li>"; // add an li for each item in the list
        }
        $output .= "</ul>"; // add the list closing tags
        return $output;
          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