...

/

Changes in v*prinf(), NULL Length Arguments, and the implode() Function

Changes in v*prinf(), NULL Length Arguments, and the implode() Function

Learn about the updated print methods and other features in PHP 8.

Dealing with v*printf() changes

The v*printf() family of functions is a subset of the printf() family of functions that includes vprintf(), vfprintf(), and vsprintf(). The difference between this subset and the main family is that the v*printf() functions are designed to accept an array as an argument rather than an unlimited series of arguments. Here is a simple example that illustrates the difference:

Press + to interact
<?php
// Define variables representing different parts of the date format.
$ord = 'third'; // Represents the ordinal indicator of the day (e.g., "first", "second").
$day = 'Thursday'; // Represents the day of the week (e.g., "Monday", "Tuesday").
$pos = 'next'; // Represents the position of the day relative to the current month (e.g., "next", "previous").
$date = new DateTime("$ord $day of $pos month"); // Create a new DateTime object based on the provided date format.
// Define the pattern to be used for displaying the date information.
$patt = "The %s %s of %s month is: %s\n";
// Display the formatted date using printf() with a series of arguments.
// The variables $ord, $day, $pos, and $date->format('l, d M Y') are used to replace the placeholders in $patt.
printf($patt, $ord, $day, $pos, $date->format('l, d M Y'));
// Create an array with the date components to be used with vprintf().
// The order of elements in the array corresponds to the placeholders in $patt.
$arr = [$ord, $day, $pos, $date->format('l, d M Y')];
// Display the formatted date using vprintf() and the array of arguments.
// The elements of $arr are used to replace the placeholders in $patt.
vprintf($patt, $arr);
?>

Let’s get into the code.

  • Lines 3–9: First, we define a set of arguments that will be inserted into a pattern, $patt.

  • Line 13: We then execute a printf() statement using a series of arguments.

  • Lines 17–21: We then define the arguments as an array, $arr, and use vprintf() to produce the same result.

In either version of PHP, the output is the same.

As we can see, the output of both functions is identical. The only usage difference is that vprintf() accepts the parameters in the form of an array.

Prior versions of PHP allowed a developer to play fast and loose with arguments presented to the v*printf() family of functions. In PHP 8, the data type of the arguments is now strictly enforced. This only presents a problem where ...