Open In App

PHP | Format Specifiers

Strings are one of the most used Datatype arguably irrespective of the programming language. Strings can be either hardcoded (specified directly by the developer) or formatted (where the basic skeleton is specified and the final string is obtained by incorporating values of other variables). Formatted strings can be defined as a set of segments where each segment may contain an integer, float or even another string.

Formatted strings use Format Specifiers to create the basic structure of the string. Format Specifiers are predefined character sequence that can be used to define the datatype to be stored or displayed as well a how any given value should be formatted i.e. precision, padding etc. Format Specifiers, in general, begin with a percentile symbol or ‘%’ followed by a character sequence that defines the datatype and desired format. When iterating over a format if any format specifier is encountered it is understood by the compiler/interpreter that there exists a corresponding directive whose value is to be formatted and used. Hence, a string may contain no format specifier at all, but if it does at least the same number of directives should be resent as well. In case of excessive directives, some languages just ignore the unrequired and let it execute with a warning.



The following is a brief discussion of the Formats and Datatypes that can be specified in PHP. Each one of them is implemented with a preceding percentile symbol or ‘%’.

Formatting Values



Datatypes

The Following code illustrates the working of different format specifiers:




<?php
  
// PHP program to illustrate Working 
// of different Format Specifiers
  
// Creating Dummy Variables 
$numValue = 5;
$strValue = "GeeksForGeeks";
  
// Using Sign Specifier.
printf("Signed Number: %+d\n",$numValue);
  
// Padding and Width Specifier.
printf("Padding and Width\n%'03d\n%'03d\n",
                    $numValue,$numValue+10);
  
// Precision Specifier.
printf("Precision: %.5f %.5s\n", $numValue, $strValue);
  
// Different DataTypes.
// Integer and Percentile.
printf("Percentage: %d%%\n",$numValue);
  
// Binary Octal and Hexadecimal Representation.
printf("Binary: %b Octal: %o Hexadecimal: %x\n",
        $numValue+10,$numValue+10,$numValue+10);
  
// Character Representation.
printf("Character: %c\n",$numValue+60);
  
// Strings.
printf("String: %s\n",$strValue);
  
// Real Numbers.
printf("RealNumber: %f\n",1/$numValue); 
  
// Scientific Numerical Representation.
printf("Scientific Representation:%e\n",$numValue+100); 
  
?>

Output:

Signed Number: +5
Padding and Width
005
015
Precision: 5.00000 Geeks
Percentage: 5%
Binary: 1111 Octal: 17 Hexadecimal: f
Character: A
String: GeeksForGeeks
RealNumber: 0.200000
Scientific Representation:1.050000e+2

Article Tags :