phpprintf

Is it safe to call sprintf() with fewer placeholders than provided values?


I'm just wondering if omitting an argument from sprintf is going to cause any issues.

I can't recall for sure, but I think on one of my sites if I omitted the arguments it error'd out, but I tried it on a different server and it's not posting any issues with all php error notices turned on.

Just want to double check!

Example:

sprintf('This is an example %s','test'); // outputs "This is an example test"
sprintf('This is an example','test'); // outputs "This is an example"

Solution

  • It will error if you pass too few arguments, but too many is fine. Just like the rest of PHP, if you pass too many arguments, they will just be ignored.

    $ php -r "echo sprintf('foo %s');"
    PHP Warning:  printf(): Too few arguments in Command line code on line 1
    PHP Stack trace:
    PHP   1. {main}() Command line code:0
    PHP   2. printf() Command line code:1
    
    Warning: printf(): Too few arguments in Command line code on line 1
    
    Call Stack:
        0.0005     314336   1. {main}() Command line code:0
        0.0006     314408   2. printf() Command line code:1
    
    $ php -r "printf('foo %s', 'foo', 'bar');"
    foo foo