Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 10 of 10 · Arrays & String Functions
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
FunctionPurposeExample
sprintf($format, ...$args)Build a formatted string using placeholderssprintf('%05d', 42) = '00042'
number_format($num, $decimals)Format a number with grouped thousands and fixed decimalsnumber_format(150000.5, 2) = '150,000.50'
str_pad($str, $len, $pad)Pad a string to a certain lengthstr_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?