14

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?

5 Answers 5

25
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.

Sign up to request clarification or add additional context in comments.

2 Comments

oh I didn't know about vsprintf. Thanks :)
Thanks a lot for that vsprint(), I wish I could upvote you more
2

Or better yet (and a bit safer too):

function some_func(string $fmt, ... $args) {
    $s = vsprintf($fmt, $args);
}

This is PHP 7.4, not sure if it works in earlier versions.

Comments

1

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

Comments

0

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.