Forum Moderators: coopster
I'm fetching a variable value from a database. It's a timezone so it's something between -12 and 12 (including 0), like:
$time_zone=$row['time_zone']; If for example,
time_zone=2 in the database,I want the script to echo "timezone:UTC+2". Is there a better way than the if loop, something like sprintf to do this? sprintf('my string with args %1$s and %3$s and timezone=%2\$+u', $arg1, "2", $arg3); or similar, and I'm getting output like "my string with args firstArg and thirdArg and timezone=$+d".
I'm desperate! Any help? Is the backslash needed? How does the formatting go? Thanks !
Btw if you work for php.net, please tell them to update the formatting documentation for multiple arguments, I smell the problem is somewhere there...
I think you want the string in the sprintf arg to be like this:
timezone:%2$d+
arg=1 (positive), the output is 1+ (instead of +1)
arg=-7 (negative), the output is -7+ ...
Looks like there is always an extra trailing "+" but no preceeding sign (even for positive number)...
Should I go for
if ($timezone>0) { $timezone = "+" . $timezone; } ? Thanks for your time.
I will mark this thread as solved (I don't even know if this is possible..!) as soon as someone explains me with a working example what the documentation (see link in post #1) means here:
Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:1. An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well, and was added in PHP 4.3.0.
I use php v5+...
echo sprintf("timezone:UTC%+d", $timezone);
Should be what you are looking for and what the documentation was talking about.
I currently use seabird's solution.
As I said in post #3, your solution in post #2 did not work (see above for output). To be honest I did not really understand what documentation says about "placeholders", but I really need them as the function
sprintf($format, $param) is in the script (and so is $param) but $format is included with a language file... So if the
$timezone is parameter #6 and the formatting is built accordingly with the doc, I should have: %6 -> the param to use (here $timezone="7" or $timezone=7, does it make a difference?) %6+ -> "optional sign specifier" to force the sign to be displayed %6+d -> to be "presented as a (signed) decimal number" The formatting string (that matches the one without placeholder you posted in the above message) is built according to the elements' order and outputs:
$timezone="7" // +7 correct $timezone="-7" // +-7 wrong... As I said seabird's code works perfectly (OK, I could tweak it to hide "UTC+0" ("UTC" is good) but I guess
sprintf() will no do that... I'm just following-up for educational purposes! Cheers...