phpprintfpadding

Empty space padded to a dynamic length shows nothing when printed


I've faced an php sprintf string in PHP Objects, patterns and practice book :

$txtout = "";
$pad = 4*$num;
$txtout .= sprintf( "%{$pad}s", "" );

I'm not sure, but I think the author is aimed to build padding(indent) based on $pad , but actually it doesn't work, is this code syntactically right?


Solution

  • it does work to add spaces or padding - it's just that in plain html generally you will not see the spaces/padding - though inside a pre tag it will become apparent.

    $num=10;
    $txtout = "";
    $pad = 4*$num;
    $txtout .= sprintf( "%{$pad}s", "" );
    
    /* you should see the word hello spaced out across the page */
    echo '<pre>',print_r( $txtout.'hello'.$txtout.'hello',true ),'</pre>';