PHP’s sprintf() or printf() Returning Blank String

January 31st, 2013 - Posted by Steve Marks to PHP, Web Development.

I ran into this problem when I recently took on some code from another developer. The code in question contained huge strings formatted using the printf() and sprintf() functions.

Whilst modifying one of these strings I ran into a problem where the returned value was completely blank. Due to the size of the strings (and the fact that error reporting was turned off) it proved to be difficult to debug but after a bit of trial and error I managed to replicate the problem on a smaller scale.

Allow me to demonstrate an example scenario where a blank value would be returned:

$my_value = sprintf(
	"The %s fox %s over the %s",
	"brown",
	"jumped"
);
echo $my_value;

Notice anything wrong here? How about that the number of arguments doesn’t match the number of ‘%s’ occurences? As a result the returned string will be blank.

To fix this we simply have to ensure that the two tally up:

$my_value = sprintf(
	"The %s fox %s over the %s",
	"brown",
	"jumped",
	"fence"
);
echo $my_value;
Tags:
This entry was posted on Thursday, January 31st, 2013 at 4:59 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first