Hướng dẫn php sprintf array

I have an array witch match string placeholders as follow:

Nội dung chính

  • Not the answer you're looking for? Browse other questions tagged php arrays printf or ask your own question.
  • 4 Answers 4
  • Your Answer
  • Sign up or log in
  • Post as a guest
  • Post as a guest
  • Not the answer you're looking for? Browse other questions tagged php arrays printf or ask your own question.

"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

asked Nov 10, 2012 at 20:16

1

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];

answered Nov 10, 2012 at 20:17

FThompsonFThompson

27.9k11 gold badges55 silver badges91 bronze badges

2

An alternative to vsprintf in PHP 5.6+

sprintf["some text %s another text %s extra text %s", ...$array];

answered Sep 16, 2016 at 9:30

user634545user634545

8,6365 gold badges26 silver badges39 bronze badges

1

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,8412 gold badges26 silver badges34 bronze badges

answered Jul 2, 2017 at 23:08

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

answered Jan 6, 2018 at 1:03

deeshankdeeshank

3,8814 gold badges24 silver badges31 bronze badges

Not the answer you're looking for? Browse other questions tagged php arrays printf or ask your own question.

I have an array witch match string placeholders as follow:

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

and the array:

$array match the first %s $array match the second %s $array 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

php arrays printf
Share
Improve this question
Follow
asked Nov 10 "12 at 20:16
tarektarek
641 2 2 gold badges 7 7 silver badges 9 9 bronze badges
1
seealso:: darkedeneurope.com/questions/5701985/… – dreftymac Feb 9 "18 at 23:20
Add a comment  |

4 Answers 4

Active Oldest Votes
65

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

Bạn đang xem: Sprintf php array

$content = vsprintf["some text %s another text %s extra text %s", $array];
Share
Improve this answer
Follow
answered Nov 10 "12 at 20:17
FThompsonFThompson
26.9k 11 11 gold badges 52 52 silver badges 87 87 bronze badges
2
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 8 "18 at 9:32
Add a comment  | 
11

An alternative to vsprintf in PHP 5.6+

sprintf["some text %s another text %s extra text %s", ...$array];
Share
Improve this answer
Follow
answered Sep 16 "16 at 9:30
user634545user634545
7,854 4 4 gold badges 23 23 silver badges 36 36 bronze badges
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. php.net/manual/en/function.sprintf.php No where says what this mixed is. – vee Oct 22 "19 at 8:19
Add a comment  | 
1

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.

Xem thêm: How To Install Linux, Apache, Mysql, Php [Lamp] Stack On Centos 6

For example in your case:

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

and the array:

$array match the first %s $array match the second %s $array 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
Share
Improve this answer
Follow
edited Jul 4 "17 at 13:42
simeg
1,785 2 2 gold badges 23 23 silver badges 34 34 bronze badges
answered Jul 2 "17 at 23:08
user8240963user8240963
Add a comment  | 
0
$rv = array[1,2,3,4]; sprintf["

yay ", print_r[$rv, true]]
Share
Improve this answer
Follow
answered Jan 6 "18 at 1:03
deeshankdeeshank
3,312 4 4 gold badges 20 20 silver badges 28 28 bronze badges
Add a comment  | 

Your Answer

Thanks for contributing an answer to Stack Overflow!

Please be sure to answer the question. Provide details and share your research!

But avoid …

Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.


Draft saved
Draft discarded

Sign up or log in


Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Submit

Post as a guest


Name
Email

Required, but never shown


Post as a guest


Name
Email

Required, but never shown


Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy


Not the answer you're looking for? Browse other questions tagged php arrays printf or ask your own question.


The Overflow Blog
Infrastructure as code: Create and configure infrastructure elements in seconds
Podcast 318: What’s the half-life of your code?
Featured on Meta
Introducing Outdated Answers project
Survey questions for outdated answers
Visit chat
Linked
17
vsprintf or sprintf with named arguments, or simple template parsing in PHP
3
How to format array out with printf in php
Related
3742
Create ArrayList from array
4293
How do I check if an array includes a value in JavaScript?
2893
How to append something to an array?
2694
Deleting an element from an array in PHP
3282
How to insert an item into an array at a specific index [JavaScript]?
3387
Loop through an array in JavaScript
4675
Reference — What does this symbol mean in PHP?
2983
How to check if an object is an array?
9190
How can I remove a specific item from an array?
4960
For-each over an array in JavaScript
Hot Network Questions
As a DM, is telling your players what their characters conclude a bad practice?
Why would an airport use an L/R runway combination and a second number instead of L/C/R?
Reconstruct an integer from its prime exponents
Conceptual difficulty with friction and inertia
Why is the Venus Climate Orbiter also called Planet-C?
Can I be a NASA astronaut as a 5 foot 6 inches 16 year old Bangladeshi girl with eyesight problems?
Adding a string to every column in a line- excluding the first column, variable line length, the string is contained in the first column of each line
Which governors can flip the Senate as of March 2021?
She sells sanctuary
Could a natural disaster completely isolate a large city in the modern world without destroying it?
How to reinforce a joist with plumbing running through it?
Sleet Storm: do crampons stop you from falling prone?
Is it possible for water to exist in fiery places?
Abnormal distance in acronym list
How can I raise my handlebars when there are no spacers above the stem?
Noise cancelling Chiron Y-axis
How to recover “deleted” files in Linux on an NTFS filesystem [files originally from macOS]
Pipetting: do human experimenters need liquid class information?
Is there any disadvantage to adding gelatin just before bottling?
Is it okay if I tell my boss that I cannot read cursive?
Need help in Identifying a late 90's early 2000's Lego Space Fighter/Bomber [Photos included]
Break keyword outside a loop is syntax error or semantic error?
Why would silk underwear disqualify you from the United States military draft?
What do the fake advertisements in WandaVision mean? more hot questions
Question feed
Subscribe to RSS
Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.


lang-php
Stack Overflow Questions Jobs Developer Jobs Directory Salary Calculator Help Mobile
Products Teams Talent Advertising Enterprise
Company About Press Work Here Legal Privacy Policy Terms of Service Contact Us
Stack Exchange Network Technology Life / Arts Culture / Recreation Science Other
Stack Overflow Server Fault Super User Web Applications Ask Ubuntu Webmasters Game Development
TeX - LaTeX Software Engineering Unix & Linux Ask Different [Apple] WordPress Development Geographic Information Systems Electrical Engineering
Android Enthusiasts Information Security Database Administrators Drupal Answers SharePoint User Experience Mathematica
Salesforce ExpressionEngine® Answers Stack Overflow em Português Blender Network Engineering Cryptography Code Review
Magento Software Recommendations Signal Processing Emacs Raspberry Pi Stack Overflow на русском Code Golf
Stack Overflow en español Ethereum Data Science Arduino Bitcoin Software Quality Assurance & Testing Sound Design
Windows Phone more [28]
Photography Science Fiction & Fantasy Graphic Design Movies & TV Music: Practice & Theory Worldbuilding Video Production
Seasoned Advice [cooking] Home Improvement Personal Finance & Money Academia Law Physical Fitness Gardening & Landscaping
Parenting more [10]
English Language & Usage Skeptics Mi Yodeya [Judaism] Travel Christianity English Language Learners Japanese Language
Chinese Language French Language German Language Biblical Hermeneutics History Spanish Language Islam
Русский язык Russian Language Arqade [gaming] Bicycles Role-playing Games Anime & Manga Puzzling
Motor Vehicle Maintenance & Repair Board & Card Games Bricks Homebrewing Martial Arts The Great Outdoors Poker
Chess Sports more [16]
MathOverflow Mathematics Cross Validated [stats] Theoretical Computer Science Physics Chemistry Biology
Computer Science Philosophy Linguistics Psychology & Neuroscience Computational Science more [10]
Meta Stack Exchange Stack Apps API Data
Blog Facebook Twitter LinkedIn Instagram

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.3.5.38726


Stack Overflow works best with JavaScript enabled


Chủ Đề