PHP - String String Formatting

Introduction

General-Purpose Formatting with printf() and sprintf()

printf() and sprintf() format strings in all sorts of ways.

printf() takes a string argument called a format string, usually followed by one or more additional arguments containing the string or strings to format.

The format string contains ordinary text mixed with one or more conversion specifications.

Each conversion specification requires an additional argument to be passed to printf().

Then it formats that argument as required and inserts it into the format string.

The resulting formatted string is displayed.

Conversion specifications always start with a percent % symbol.

Demo

<?php
printf( "Pi rounded to a whole number is: %d", M_PI );
?>

Result

Here, %d" is the format string, and the "%d" within the string is a conversion specification.

PHP constant M_PI represents an approximation of pi to a number of decimal places.

Here's another example that uses multiple conversion specifications:

Demo

<?php
printf( "%d times %d is %d.", 2, 3, 2*3 );
?>

Result

This code displays three decimal numbers within the output string: 2, 3, and the result of the expression 2*3.

Related Topics