How to Use vfprintf() Function in PHP 8.4 and PHP 8.5?

The vfprintf() function works essentially the same in PHP 8.4 and PHP 8.5. There are no breaking changes or new features specific to PHP 8.4. For PHP 8.5, a minor bug fix regarding precision formatting is noted, but it does not change the basic usage of the function.

Function

vfprintf() writes a formatted string to a specific stream (like a file). It works just like fprintf(), but it accepts the arguments as an array instead of a variable number of separate parameters.

Signature:

vfprintf(resource $stream, string $format, array $values): int

Example

A common use case is writing a formatted date directly to a file, similar to the official PHP documentation example.

<?php
// Open a file for writing
$fp = fopen( date.txt , w );
if (!$fp) {
   return;
}

$year = 2026;
$month = 11;
$day = 15;

// Write the formatted date (e.g., "2026-11-15") to the file
vfprintf($fp, "%04d-%02d-%02d", array($year, $month, $day));

fclose($fp);
?>

In this example, the array array($year, $month, $day) is unpacked and passed to the format string "%04d-%02d-%02d", writing the result to date.txt.

22 Views