How to use printf in PHP

In this article I will explain how the printf() function can be used in PHP.
  • 1475

printf() function in PHP

  • The printf() function is used to output a formatted string.
  • In printf() function, The arg1, arg2, ++ parameters will be added at percent (%) signs in the main string.
  • The printf() function works "step-by-step".
  • In printf() function, you must use placeholders, If there are more % signs than arguments

Syntax

printf(format,arg1,arg2,arg++)

Parameter

  • format format is required parameter. Determine the string and how to format the variables in it.

    Possible format values:

    • %% - It's return a percent sign.
    • %b - It is represent binary number.
    • %c - The character according to the ASCII value.
    • %d - It is represent signed decimal number.
    • %e - It is represent scientific notation.
    • %u - It is represent unsigned decimal number.
    • %f - It is represent floating-point number.
    • %F - It is represent floating-point number.
    • %o - It is represent octal number.
    • %s - It is represent String.
    • %x - It is represent Hexadecimal number (lowercase letters).
    • %X - It is represent Hexadecimal number (uppercase letters).

    Additional format values. These are placed between the % and the letter.

    • + (Forces both + and - in front of numbers. By default, only negative numbers are marked)
    • ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier)
    • - (Left-justifies the variable value)
    • [0-9] (Specifies the minimum width held of to the variable value)
    • .[0-9] (Specifies the number of decimal digits or maximum string length)
  • arg1 arg1 is required parameter. The argument to be inserted at the first %-sign in the format string.
  • arg2 arg2 is optional parameter. The argument to be inserted at the second %-sign in the format string.
  • arg++ arg++ is optional parameter. The argument to be inserted at the third, fourth, etc. %-sign in the format string.

Example

The following example show to how the printf() function can be used in PHP.

<html>

<body>

<h3 style="color: darkblue;">printf() function example in PHP</h3>

    <?php

    $str = "Hello";

    $num = 999;

    printf("%s C-sharpcorner user. you visit number is %u",$str,$num);

    ?>

</body>

</html>

 

Output

printf-php.gif
You may also want to read these related articles here
 
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.