37

I have an array witch match string placeholders as follow:

"some text %s another text %s extra text %s"

and the array:

$array[0] match the first %s 
$array[1] match the second %s 
$array[2] match the third %s 

I thought it could be done using the sprintf function as follow:

$content = sprintf("some text %s another text %s extra text %s", $array);

but this return the too few arguments error, i tried to use implode:

$content = sprintf("some text %s another text %s extra text %s", implode(",",$array));

thanks in advance

tarek
  • 751
  • 2
  • 7
  • 9

4 Answers4

81

Use vsprintf instead of sprintf. It takes an array parameter from which it formats the string.

$content = vsprintf("some text %s another text %s extra text %s", $array);
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • yep that's right, thank you, 7 more minutes to accept the answer :) – tarek Nov 10 '12 at 20:24
  • in `PHP 5.6.33`, `$content` is the length of `formatted string`; we can try `$string = 'Hello %name!'; $data = array( '%name' => 'John' ); $greeting = str_replace(array_keys($data), array_values($data), $string);` from first comment of above link of `vsprintf` – Cheney Mar 08 '18 at 09:32
18

An alternative to vsprintf in PHP 5.6+

sprintf("some text %s another text %s extra text %s", ...$array);
user634545
  • 9,099
  • 5
  • 29
  • 40
  • 1
    This answer works very well. I do not understand that php sprintf document said second parameter is **mixed** type but throwing error if it is an array. https://www.php.net/manual/en/function.sprintf.php No where says what this **mixed** is. – vee Oct 22 '19 at 08:19
3

Here you have to use vsprintf() instead of sprintf().

sprintf() accepts only plain variables as argument. But you are trying to pass an array as argument.

For that purpose you need vsprintf() which accepts array as argument.

For example in your case:

"some text %s another text %s extra text %s"

and the array:

$array[0] match the first %s 
$array[1] match the second %s 
$array[2] match the third %s 

To achieve what you want you have to do the following:

$output = vsprintf("some text %s another text %s extra text %s",$array);
echo $output;

Output:

some text match the first another text match the second extra text match the third
simeg
  • 1,889
  • 2
  • 26
  • 34
0
$rv = array(1,2,3,4);
sprintf('[deepak] yay [%s]', print_r($rv, true))
deeshank
  • 4,286
  • 4
  • 26
  • 32