Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php sprintf with array

Tags:

arrays

php

printf

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

like image 217
tarek Avatar asked Nov 10 '12 20:11

tarek


People also ask

Is Sprintf PHP safe?

Not in any traditional sense, as PHP's sprintf doesn't support any of the really dangerous conversions like %n . A user-controlled format string can still cause some limited havoc (consider %99999999s ), but about the worst I think it could do would be to consume memory and time. Save this answer.

Is the use of sprintf () function in PHP?

The sprintf() is an in-built function of PHP which writes a formatted string to a variable. It returns a formatted string.

What does %s mean in PHP?

%s is a type specifier which will be replaced to valuable's value (string) in case of %s . Besides %s you can use other specifiers, most popular are below: d - the argument is treated as an integer, and presented as a (signed) decimal number.

What is Vsprintf in C?

The vsprintf is defined in the stdio. h header file. It uses a format string and corresponding arguments to generate a string stored in the provided destination string.


2 Answers

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); 
like image 132
FThompson Avatar answered Oct 02 '22 16:10

FThompson


An alternative to vsprintf in PHP 5.6+

sprintf("some text %s another text %s extra text %s", ...$array); 
like image 39
user634545 Avatar answered Oct 02 '22 18:10

user634545