hey guys!

I can't seem to get the syntax correct for this. I'm trying to put in different options inside a string:


$x =42
echo 'blah' if($x == 42){' blue '}'blah';

I think you get the general idea. I've tried this a few different ways, using {.' blue '.}
and using '.if($x==42){'blue'}. the latter not making any sense of course because the if statement is not a string but I figured I'd try. I realize I could just do something like this:

if($x=42) {$y=' blue '}
echo 'blah'.$y.'blah';

but I'm interested in knowing the proper way to insert the php inside the string itself. Thanks for your time!

-slight 🙂

    How about:

    $output = "blah";
    if ($x == 42) { $output.= " blue "; }
    $output.= "blah";
    echo $output;
    

    There may well be a more elegant way of doing it.

      You can't put an IF statement inside of a string. Try this:

      $x =42
      if($x == 42)
          echo 'blue blah';
      else
          echo 'blah';
      

      Or if you want to be elegant and concise:

      $x = 42;
      echo ($x == 42) ? 'blue blah' : 'blah';
      

        Wow...

        Bonesnap;10989872 wrote:
        echo ($x == 42) ? 'blue blah' : 'blah';
        
        • excellent, and way more concise than mine!
          phpSimon;10989870 wrote:

          How about:

          $output = "blah";
          if ($x == 42) { $output.= " blue "; }
          $output.= "blah";
          echo $output;
          

          There may well be a more elegant way of doing it.

          what on earth is .= ? why is that dot there? OH just figured it out..

            Just because TMTOWTDI:

            blah <?php if($x == 42) { ?>blue <?php } ?>blah
            
            printf("blah %sblah", ($x == 42) ? "blue " : "");
            
            echo "blah ";
            if($x == 42) {
                echo "blue ";
            }
            echo "blah";
            

              Also, you can nest a ternary in a string with concatenation:

              echo 'blah' . ($x==42 ? 'blue' : '') . 'blah';
              
                Derokorian;10990038 wrote:

                Also, you can nest a ternary in a string with concatenation:

                echo 'blah' . ($x==42 ? 'blue' : '') . 'blah';
                

                I had decided not to go there. 😉 :p

                  Write a Reply...