41

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

1

4 Answers 4

87

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);
Sign up to request clarification or add additional context in comments.

2 Comments

yep that's right, thank you, 7 more minutes to accept the answer :)
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
21

An alternative to vsprintf in PHP 5.6+

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

2 Comments

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. php.net/manual/en/function.sprintf.php No where says what this mixed is.
I'd recommend using ...array_values($array) instead of ...$array in case your array has named keys (which would result in sprintf() does not accept unknown named parameters without the array_values wrapper)
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

Comments

0
$rv = array(1,2,3,4);
sprintf('[deepak] yay [%s]', print_r($rv, true))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.