PHP String vprintf() Function



The PHP String vprintf() function is used to display array values as a formatted string. Print array values as a formatted string based on format. It works similarly to printf(), but accepts an array of parameters instead of a variable number of arguments. When successful, it returns the length of the outputted string.

Syntax

Below is the syntax of the PHP String vprintf() function −

int vprintf ( string $format, array $values )

Parameters

Here are the parameters of the vprintf() function −

  • $format − (Required) It is used to specify how the string will be formatted.

  • $values − (Required) It is an array of arguments to be put between the% signs in the format string.

Return Value

The vprintf() function returns the length of the outputted string.

PHP Version

First introduced in core PHP 4.1.0, the vprintf() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

Below is the basic example of the PHP String vprintf() function to output a formatted string.

<?php
   $number = 22;
   $str = "Tutorials point";

   vprintf("There are %u million users for %s.",array($number,$str));
?>

Output

Here is the outcome of the following code −

There are 22 million users for Tutorials point.

Example 2

In the below PHP code we will use the vprintf() function and format a simple string with two placeholders and show the values from an array.

<?php
   // Define format variable here
   $format = "Name: %s, Age: %d\n";
   $values = ["Alisha", 30];

   vprintf($format, $values); 
?> 

Output

This will generate the below output −

Name: Alisha, Age: 30

Example 3

Now the below code show the usage of vprintf() function for formatting with different data types.

<?php
   $format = "Product: %s, Quantity: %d, Price: %.2f\n";
   $values = ["Book", 10, 2000.00];

   vprintf($format, $values); 
?> 

Output

This will create the below output −

Product: Book, Quantity: 10, Price: 2000.00

Example 4

In the following example, we are using the vprintf() function to show how to use padding with alignment in the format string.

<?php
   $format = "| %-10s | %5d | %8.2f |\n";
   $values1 = ["Alisha", 30, 2500.50];
   $values2 = ["Shalini", 25, 1500.00];

   vprintf($format, $values1);
   vprintf($format, $values2);
?> 

Output

Following is the output of the above code −

| Alisha     |    30 |  2500.50 |
| Shalini    |    25 |  1500.00 |
php_function_reference.htm
Advertisements