note 102709 modified in language.types.string by danbrown

From: Date: Tue, 01 Mar 2011 21:14:39 +0000
Subject: note 102709 modified in language.types.string by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-177463@lists.php.net to get a copy of this message
I recently discovered the joys of using heredoc with sprintf and positions. Useful if you want some code to iterate, you can repeat placeholders. <?php function getNumber($num = 0) { $foo = rand(1,20); return ($foo + $num); } function getString() { $foo = array("California","Oregon","Washington"); shuffle($foo); return $foo[0]; } function getDiv() { $num = getNumber(); $div = sprintf( "<div>%s</div>", getNumber(rand(-5,5)) ); return $div; } $string = <<<THESTRING I like the state of %1\$s <br /> I picked: %2\$d as a number, <br /> I also picked %2\$d as a number again <br /> %3\$s<br /> %3\$s<br /> %3\$s<br /> %3\$s<br /> %3\$s<br /> THESTRING; $returnText = sprintf( $string, getString(),getNumber(),getDiv() ); echo $returnText; ?> Expected output of the above code: I like the state of Oregon I picked: 15 as a number, I also picked 15 as a number again 5 5 5 5 5 --was-- I recently discovered the joys of using heredoc with sprintf and positions. Useful if you want some code to iterate, you can repeat placeholders. <?php function getNumber($num = 0) { $foo = rand(1,20); return ($foo + $num); } function getString() { $foo = array("California","Oregon","Washington"); shuffle($foo); return $foo[0]; } function getDiv() { $num = getNumber(); $div = sprintf( "<div>%s</div>", getNumber(rand(-5,5)) ); return $div; } $string = <<<THESTRING I like the state of %1\$s <br /> I picked: %2\$d as a number, <br /> I also picked %2\$d as a number again <br /> %3\$s<br /> %3\$s<br /> %3\$s<br /> %3\$s<br /> %3\$s<br /> THESTRING; $returnText = sprintf( $string, getString(),getNumber(),getDiv() ); echo $returnText; ?> http://php.net/manual/en/language.types.string.php

« previous php.notes (#177463) next »