PHP String Formatting
In this page:
printf("format with %s and %d", $string, $number);
$text = sprintf("%.2f", $float); // returns the string instead of printing
Basic printf Output
printf() placeholders इस्तेमाल करके एक formatted string बनाता है — string के लिए %s, integer के लिए %d — और हर placeholder corresponding argument की value से भर जाने के बाद तुरंत result print करता है।
उदाहरण: Basic printf Output
<?php
// Call `printf("Name: %s, Age: %d", "Alice", 30)`
printf("Name: %s, Age: %d", "Alice", 30);
?>
Login to try C/C++/Java/PHP code in the editor
Formatted Strings Return करना
sprintf() printf() जैसा ही exact placeholder syntax इस्तेमाल करता है, लेकिन result तुरंत print करने के बजाय, यह formatted string को एक value की तरह return करता है — आपको इसे store करने, किसी दूसरे function को pass करने, या इसे output करना है या नहीं decide करने से पहले इसे build करने देते हुए।
उदाहरण: Returning Formatted Strings
<?php
// Declare `$formatted`, set to `sprintf("Name: %s, Age: %d", "Alice", 30)`
$formatted = sprintf("Name: %s, Age: %d", "Alice", 30);
// Print `$formatted` to the output
echo $formatted;
?>
Login to try C/C++/Java/PHP code in the editor
Decimals Format करना
%.2f जैसा एक format specifier control करता है कि किसी float को format करते समय decimal point के बाद exactly कितने digits दिखें — 3.14159 पर %.2f '3.14' produce करता है, truncate करने या पूरी precision print करने के बजाय दो decimal places तक round करते हुए।
उदाहरण: Formatting Decimals
<?php
// Call `printf("%.2f", 3.14159)`
printf("%.2f", 3.14159);
?>
Login to try C/C++/Java/PHP code in the editor
number_format इस्तेमाल करना
number_format() पैसे और दूसरे बड़े numbers दिखाने के लिए purpose-built है: यह automatically thousands separators insert करता है और आपको एक fixed decimal precision specify करने देता है, 1234567.891 को एक ही call में एक reader-friendly '1,234,567.89' में बदलते हुए।
उदाहरण: Using number_format
<?php
// Print `number_format(1234567.891, 2)` to the output
echo number_format(1234567.891, 2);
?>
Login to try C/C++/Java/PHP code in the editor
sprintf से Strings Pad करना
sprintf() के width specifiers (जैसे %10s) किसी value को एक fixed total width तक pad करते हैं, ज़रूरत के हिसाब से right- या left-align करते हुए।
यह fixed-width alignment exactly वह है जो आपको tabular data print करते समय चाहिए जिसे evenly spaced columns में visually align होना है।
उदाहरण: Padding Strings with sprintf
<?php
// Call `printf("[%10s]\n", "hi")`
printf("[%10s]\n", "hi");
// Call `printf("[%-10s]", "hi")`
printf("[%-10s]", "hi");
?>
Login to try C/C++/Java/PHP code in the editor
- गलत placeholder इस्तेमाल करना, जैसे एक decimal number के लिए
%d, जो इसे truncate करके एक integer बना देता है। printfको placeholders से कम arguments pass करना, जो एकArgumentCountErrorthrow करता है।number_format()इस्तेमाल करना और फिर result पर math करना, जबकि यह commas वाली एक string return करता है, कोई number नहीं।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: