Interview question
How do you format strings and numbers in PHP? (sprintf, number_format, str_pad) PHP में strings और numbers कैसे format करें? (sprintf, number_format, str_pad)
Answer
| Function | Purpose | Example |
|---|---|---|
| sprintf($format, ...$args) | Build a formatted string using placeholders | sprintf('%05d', 42) = '00042' |
| number_format($num, $decimals) | Format a number with grouped thousands and fixed decimals | number_format(150000.5, 2) = '150,000.50' |
| str_pad($str, $len, $pad) | Pad a string to a certain length | str_pad('7', 3, '0', STR_PAD_LEFT) = '007' |
$price = 149999.999;
echo number_format($price, 2); // '150,000.00'
$orderId = 42;
echo sprintf('ORD-%04d', $orderId); // 'ORD-0042'Interview tip: A very practical follow-up: how would you generate invoice numbers like INV-000123? Answer: sprintf('INV-%06d', $id) or str_pad((string)$id, 6, '0', STR_PAD_LEFT).
| Function | उद्देश्य | उदाहरण |
|---|---|---|
| sprintf($format, ...$args) | placeholders से formatted string बनाना | sprintf('%05d', 42) = '00042' |
| number_format($num, $decimals) | number को grouped thousands और fixed decimals से format करना | number_format(150000.5, 2) = '150,000.50' |
| str_pad($str, $len, $pad) | string को एक निश्चित length तक pad करना | str_pad('7', 3, '0', STR_PAD_LEFT) = '007' |
$price = 149999.999;
echo number_format($price, 2); // '150,000.00'
$orderId = 42;
echo sprintf('ORD-%04d', $orderId); // 'ORD-0042'इंटरव्यू टिप: एक practical follow-up: INV-000123 जैसे invoice numbers कैसे बनाएं? जवाब: sprintf('INV-%06d', $id) या str_pad((string)$id, 6, '0', STR_PAD_LEFT)।
Was this answer clear?