Skip to content
Advertisement

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.

But my question is, is there maybe an standard PHP solution out there to achieve this or is there another way, maybe with a simple PHP templating provided by PEAR, that I can achieve this by sticking to standard PHP?

Thanks for any help.

Advertisement

Answer

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 😉

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement