Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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);
}

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

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 :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top