TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
Advertisement
Associates
Associates
techtuts Darkmindz
CSS Tutorials Tutorialsphere.com - Free Online Tutorials
Boston PHP SurfnLearn
Reply
 
LinkBack (1) Thread Tools Search this Thread Display Modes
Old 09-16-2007, 07:15 PM   1 links from elsewhere to this Post. Click to view. #1 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 713
Thanks: 2
Salathe is on a distinguished road
Default Don't repeat yourself when using printf!

Hi folks,

We all use printf (or sprintf) to help ourselves when mingling together output strings with our variables, right? This is a tip that I use often, but I continually see people writing code where this technique would be useful but isn't used. What am I on about? Well, how many times have you seen people write something similar to this:
PHP Code:
echo '<ul>';
foreach (
$aItems as $aItem)
{
    
// E.g., <li><a href="link.html" title="Link 2">Link 2</a> (link.html)</li>
    
printf('<li><a href="%s" title="%s">%s</a> (%s)</li>',
           
$aItem['link'],
           
$aItem['title'],
           
$aItem['title'],
           
$aItem['link']);
}
echo 
'</ul>'
Notice that in the printf call, there are a number of repeated arguments (2 x $aItem['link'], and 2 x $aItem['title']). Wouldn't it be great if we could satisfy the lazy side within all of us and not repeat ourselves? Well, it's possible! Take a look at the amended example below:
PHP Code:
printf('<li><a href="%1$s" title="%2$s">%2$s</a> (%1$s)</li>',
       
$aItem['link'],
       
$aItem['title']); 
Ok, I admit for those of you not well versed in using this (or those who didn't look at the code very hard) might well be a little lost right now. What's with the extra stuff messing up our nice, normal "%s" placeholders?

Well, the extra stuff is what helps us to be lazy! The "1$" and "2$" allow us to point to the argument number which will fill in that particular placeholder. In the code above, 1$ refers to $aItem['link'] and 2$ refers to $aItem['title']. The numbers preceding the dollar sign simply reference the order of the arguments fed into the function call. What makes things useful for us, in this instance, is that the numbered replacements can be repeated any number of times within the template string without the need to add more (of the same) arguments as we did in the original example up above!

Finally, here is another example which hopefully should help to cement things into your own mind about using numbered placeholders in your (s)printf function calls:
PHP Code:
$szAdjective 'fluffy';
$szNoun 'cat';

// Both methods will output the following:
//     Yesterday, I saw a cat. It was a fluffy cat! 
//     I have never seen a cat quite so fluffy.

// Old-school method
printf('Yesterday, I saw a %s. '.
       
'It was a %s %s! I have '.
       
'never seen a %s quite so %s.',
       
$szNoun,
       
$szAdjective,
       
$szNoun,
       
$szNoun,
       
$szAdjective);

// Sexy, lazy method
printf('Yesterday, I saw a %1$s. '.
       
'It was a %2$s %1$s! I have '.
       
'never seen a %1$s quite so %2$s.',
       
$szNoun,
       
$szAdjective); 
Be lazy, use numbered placeholders! :)
__________________
Salathe is offline  
Reply With Quote
Old 09-25-2007, 10:50 PM   #2 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,587
Thanks: 72
Wildhoney is on a distinguished road
Default

Be lazy indeed! I've seen this on my travels, but in admission, I've never actually really taken the time to learn it. I have now!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 09-25-2007, 11:23 PM   #3 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 713
Thanks: 2
Salathe is on a distinguished road
Default

Just wait until you start using placeholders like %1$'x-10.20s, then it gets really interesting! Yes, that is a single placeholder like %s.
__________________
Salathe is offline  
Reply With Quote
Old 09-25-2007, 11:26 PM   #4 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,587
Thanks: 72
Wildhoney is on a distinguished road
Default

You know what your next article is then :) !
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 09-25-2007, 11:30 PM   #5 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 713
Thanks: 2
Salathe is on a distinguished road
Default

I think I may have scared people away with this article (judging by the huge list of comments), never mind getting into the relative complexities of the optional parameters within the placeholders! Though if someone asks, it might be good to write up a quick lesson. :)
__________________
Salathe is offline  
Reply With Quote
Old 11-23-2007, 09:23 PM   #6 (permalink)
The Frequenter
 
ReSpawN's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 445
Thanks: 49
ReSpawN is on a distinguished road
Default

Ooh hell no. I've tested in the program I call sandbox (part of my CMS for testing wild idea's of mine) and I must say, wow.

Tripping down the code here (nubstyle).

PHP Code:
# First we define the replacements right? Ok here we go.
$firstReplacement 'dang';
$secondReplacement 'it';

# Same way, the lazy way.
printf('Oh man, today I saw this chick and may I say %1$s %2$s!'$firstReplacement$secondReplacement); 
Which displayed:
Quote:
Oh man, today I saw this chick and may I say dang it!
Only tell me one thing, how could I make this practical?
Send a message via MSN to ReSpawN
ReSpawN is offline  
Reply With Quote
Old 11-23-2007, 10:03 PM   #7 (permalink)
The Acquainted
 
Join Date: Sep 2007
Location: Arizona
Posts: 114
Thanks: 10
Andrew is on a distinguished road
Default

Very nice article, and good to know. I've never gotten to the point where I've repeated myself in a sprintf() or printf() statement, but now I never will have to.
Send a message via AIM to Andrew Send a message via MSN to Andrew
Andrew is offline  
Reply With Quote
Reply


LinkBacks (?)
LinkBack to this Thread: http://www.talkphp.com/tips-tricks/1129-dont-repeat-yourself-when-using-printf.html
Posted By For Type Date
PHP Miscellaneous Do not Repeat Yourself when using Printf! Tutorial This thread Refback 01-06-2008 07:56 AM

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 10:05 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0