Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP String vsprintf() Function



The PHP String vsprintf() function is used to display array values as a formatted string. The array elements will be put between the percentage (%) signs in the main string. Display array values as a formatted string, and accept an array parameter instead of a variable number of arguments. The function returns a prepared string.

Syntax

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

string vsprintf ( string $format, array $values )

Parameters

Here are the parameters of the vsprintf() function −

  • $format − (Required) It is used to specifies string and how to format the variable in it.

  • $values − (Required) It is used to specifies an array with argument to be inserted.

Return Value

The vsprintf() function returns array values as a formatted string according to te value of format variable.

PHP Version

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

Example 1

Here is the basic example of the PHP String vsprintf() function to display array values as formatted string.

<?php
   print vsprintf("%04d-%02d-%02d", explode('-', '1990-12-25'));
?>

Output

Here is the outcome of the following code −

1990-12-25

Example 2

In the below PHP code we will try to use the vsprintf() function and format a single number with leading zeros.

<?php
   // Format with 3 digits
   $format = "Number: %03d"; 
   
   // Array with one value
   $values = [5]; 

   $result = vsprintf($format, $values);
   echo $result; 
?> 

Output

This will generate the below output −

Number: 005

Example 3

Now the below code uses the vsprintf() function and formats a date in a readable format using array of numbers.

<?php
   // Format: YYYY-MM-DD
   $format = "%04d-%02d-%02d"; 
   
   // Year, Month, Day
   $values = [2024, 12, 25]; 

   $result = vsprintf($format, $values);
   echo $result; 
?> 

Output

This will create the below output −

2024-12-25

Example 4

In the following example, we are using the vsprintf() function to format a receipt line with currency, quantity and item name.

<?php
   // Define format variable here
   $format = "Item: %s | Quantity: %02d | Total: Rs.%.2f"; 
   
   // Item name, quantity and total price
   $values = ["Notebook", 3, 1200.00]; 

   $result = vsprintf($format, $values);
   echo $result; 
?> 

Output

Following is the output of the above code −

Item: Notebook | Quantity: 03 | Total: Rs.1200.00
php_function_reference.htm
Advertisements