Using PHP Variables Inside of a String

·

,

·

Something that never fails to trip me up and that I have to google every single time I want to do it is when using PHP variables inside of a string.

For example, suppose I want to output some options to be used in a dropdown of different date formats. The first tactic that always comes to mind is to do this:

echo '<option value="short">' . esc_html( $short_date ) . '</option>
      <option value="medium">' . esc_html( $medium_date ) . '</option>
      <option value="long">' . esc_html( $long_date ) . '</option>' );

The Faster, Better Way

But it’s annoying to have to interrupt the string every time you want to insert a variable. So instead, you can just do this:

echo "<option value='short'>$short_date</option>
      <option value='medium'>$medium_date</option>
      <option value='long'>$long_date</option>";

(Note that in this example I’m assuming that you’ve already escaped the variables beforehand.)

The key is to use double quotes around your string; single quotes won’t work. This is contradictory to how PHP strings are typically written, and is likely why I can never remember the proper syntax.

The difference between single and double quotes is an important one though – double quotes around a string means that its content will be evaluated, and those variables will be swapped out with their corresponding values when executed. Single quotes just spit out whatever text is between them.

I know this is probably second nature for seasoned PHP developers, but it’s a subtlety that I always seem to have difficulty remembering. Hopefully, now that I’ve written a post about it, I’ll finally be able to retain this information.

 

 

Tags:

Comments

2 Responses to “Using PHP Variables Inside of a String”

  1. This syntax is much cleaner! I would add though, that you should (using either method) make sure that the variables are properly escaped before being included. In your example, this would be passing the variables through esc_html() first.

    1. Thanks Shawn! You’re actually not the first person to call me out on this. I’ve updated the post so as not to propagate a security issue.

      Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *