Why isn’t printf() in PHP working when I use double quotation marks?

printf("by %1$s on %2$s", 'string1', 'string2'); doesn’t work, whereas printf('by %1$s on %2$s', 'string1', 'string2'); does.

I’m actually designing a WordPress theme, and following the original twentyten theme very closely. The weird thing is, I’ve been using double quotation marks on all my previous printf() statements without any problems whatsoever.

Related posts

Leave a Reply

4 comments

  1. It is very important to realize php is treating single quoted and double quoted strings differently.

    You can read more in official php docs, but let me give you a highlight:

    $t = 'bla';
    echo '$t';
    

    will output $t, where

    $t = 'bla';
    echo "$t";
    

    will output bla

  2. That’s because you have the ‘$s’ bit in your string. When using double quotation marks PHP interprets it as a variable and tries to parse it. You probably used double quotations without the $ in it earlier.

  3. As the other answers say, it treats $s as a variable, you could always escape the $

    printf("by %1$s on %2$s", 'string1', 'string2');
    

    I would however use single quotation marks, as php doesn’t need to parse the string and is therefore faster.