PHP - String Format Swapping Arguments

Introduction

The order of the additional arguments passed to printf() must match the order of the conversion specifications within the format string.

You can change the order of the conversion specifications without being able to change the order of the arguments.

You can swap argument that comes in.

After each percentage (%) symbol, add the position of the argument you want to refer to.

1 is the first argument after the format string, 2 is the second, and so on, followed by a dollar ($) symbol.

Demo

<?php

$mailbox = "Inbox";
$totalMessages = 36;//  w ww.  j  a v a 2 s .  c o  m
$unreadMessages = 4;
printf("You have %d messages in your %s, of which %d are unread", $totalMessages, $mailbox, $unreadMessages);
printf("Your %2$s contains %3$d unread messages, and %1$d messages in total.", $totalMessages, $mailbox, $unreadMessages);
?>

Result

A variant of printf() is fprintf(), which writes the resulting string to an open file.

Related Topic