views:

409

answers:

4

I would like to write a function that (amongst other things) accepts a variable number of arguments and then passes them to sprintf().

For example:

<?php
function some_func($var) {
  // ...
  $s = sprintf($var, ...arguments that were passed...);
  // ...
}

some_func("blah %d blah", $number);
?>

How do I do this in PHP?

A: 

use $numargs = func_num_args(); and func_get_arg(i) to retrieve the argument

Stefan Ernst
A: 

Here is the way:

http://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list

basically, you declare your function as usual, without parameters, then you call func_num_args() to find out how many arguments they passed you, and then you get each one by calling func_get_arg() or func_get_args(). That's easy :)

Palantir
A: 

use a combination of func_get_args and call_user_func_array

function f($var) { // at least one argument
  $args = func_get_args();
  $s = call_user_func_array('sprintf', $args);
}
knittl
+2  A: 
function some_func() {
    $args = func_get_args();
    $s    = call_user_func_array('sprintf', $args);
}

// or

function some_func() {
    $args = func_get_args();
    $var  = array_shift($args);
    $s    = vsprintf($var, $args);
}

The $args temporary variable is necessary, because func_get_args cannot be used in the arguments list of a function in PHP versions prior to 5.3.

Ionuț G. Stan
`vsprintf` is a really good idea!
knittl
oh I didn't know about vsprintf. Thanks :)
Rob
vsprintf all the way
David Caunt
Thanks a lot for that vsprint(), I wish I could upvote you more
sandeepan