Monday 16 July 2018

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

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:

  1. $my_value = sprintf(  
  2.     "The %s fox %s over the %s",  
  3.     "brown",  
  4.     "jumped"  
  5. );  
  6. 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:

  1. $my_value = sprintf(  
  2.     "The %s fox %s over the %s",  
  3.     "brown",  
  4.     "jumped",  
  5.     "fence"  
  6. );  
  7. echo $my_value

0 comments:

Post a Comment