Ever wanted to control how numbers, dates, and text appear in PHP? **String formatting** lets you style text like a pro! 🕶️ Whether you want to format currency, align text, or control decimals, PHP has got you covered.
🔹 Formatting Strings with printf()
The printf()
function formats and prints text using placeholders.
<?php $name = "Alice"; $age = 25; printf("My name is %s and I am %d years old.", $name, $age); ?>
Output: My name is Alice and I am 25 years old.
Here:
%s
→ Replaced with a string ($name
).%d
→ Replaced with an integer ($age
).
🔹 Storing Formatted Strings with sprintf()
Want to **store** formatted text instead of printing it? Use sprintf()
.
<?php $price = 49.99; $formatted_price = sprintf("Price: $%.2f", $price); echo $formatted_price; ?>
Output: Price: $49.99
Why sprintf()
? Unlike printf()
, it **doesn’t print** immediately—it returns a formatted string instead.
🔹 Formatting Numbers with number_format()
Need to format big numbers with commas? Use number_format()
!
<?php $big_number = 1234567.8910; echo number_format($big_number, 2); ?>
Output: 1,234,567.89
Parameters:
- First argument → The number to format.
- Second argument → Number of decimal places.
🔹 Formatting Strings with Padding
Want text to align neatly? Use printf()
with padding.
<?php printf("|%-10s|%-5d|", "Item", 100); ?>
Output: |Item |100 |
(Left-aligned text, fixed width!)
🎯 Key Takeaways
printf()
→ Formats and prints strings.sprintf()
→ Formats strings and stores them.number_format()
→ Formats large numbers with commas.
📝 Practice Time!
Try formatting your own numbers, prices, and text! Maybe format your bank balance to look richer than it is! 💰😂