PHP’s sprintf() or printf() Returning Blank String
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;
0 comments:
Post a Comment