Search code examples
phptemplatesprintfnamed-parameters

vsprintf or sprintf with named arguments, or simple template parsing in PHP


I'm searching for a way to use named arguments for sprintf or printf.

Example:

sprintf(
  'Last time logged in was %hours hours, 
   %minutes minutes, %seconds seconds ago'
  ,$hours,$minutes, $seconds
);

or via vsprintf and an associative array.

I have found some coding examples here

function sprintfn ($format, array $args = array())

http://php.net/manual/de/function.sprintf.php

and here

function vnsprintf( $format, array $data)

http://php.net/manual/de/function.vsprintf.php

where people wrote their own solutions.

Is there a built-in PHP function to achieve this?


Solution

  • As far as I know printf/sprintf does not accept assoc arrays.

    However it is possible to do printf('%1$d %1$d', 1);

    Better than nothing ;)