PHP - sprintf (to the finish line)
PHP string concatenation never has to be a drag - sprintf() is waiting for you to unleash its power! Macromedia uses it, most PHP developers abuse it - shouldn't you?!

 

PHP - sprintf (to the finish line)

PHP string concatenation never has to be a drag - sprintf() is waiting for you to unleash its power! Macromedia uses it, most PHP developers abuse it - shouldn't you?!

This tutorial assumes you are comfortable with basics of DreamweaverMX/Ultradev and have already started something in PHP; both beginner and intermediate examples are presented.


A powerful built-in function of PHP is sprintf() which formats any given string into our chosen shape or form ...string based of course. So you can be familiar with the syntax of sprintf, here's the rundown:

<? sprintf(string format, parameter); ?>

Now don't get confused with its' string format portion, it's not like date/time formatting but actually the new concatenated string you want.

So how does sprintf do cool stuff?

Well, within the string format you can add parameters starting with a percent sign (%) that will be replaced by the parameter - here's a useless example using sprintf:

<? sprintf("%s World", "Hello"); ?>
Outputs: Hello World

A common way in PHP to insert a variable in a sentence is typing the variable in the sentence like:

<?php
$variableA = "Dogs";
echo("$variableA burry their bones");
?>
OUTPUTS: Dogs burry their bones!

Take note the variable is within the quotes. Others would concatenate it using the period ( . ) like:

<?php
$variableA = "Dogs";
echo($variableA ." burry their bones ");
?>
OUTPUTS: Dogs burry their bones!

Notice our second example had only the static text in quotes while the variable is out on it's own. Both are fine, and perfectly valid. Let's see a full sentence example using sprintf:

<?php
$variableA = "dogs";
echo(sprintf("How do %s burry their bones?", $variableA));
?>
OUTPUTS: How do dogs burry their bones?

You'll notice there's a %s where our parameter is within the sentence. The most common used % replacements are:

  • %s is for strings (text)
  • %d is for digits (integers/numbers)

I mention two popular replacements, so now let's use both:

<?php
$variableA = "dogs";
$variableB = 5;
echo(sprintf("How do %s burry %d bones?", $variableA, $variableB));
?>
OUTPUTS: How do dogs burry 5 bones?

Right away you'll see both %s and %d in the sentence we want to play with, and after that you'll notice the parameter of the sprintf is now parameters separated by commas. So you see that sprintf can be as wild as you want, just add commas!

If you have a "Welcome" text to your users when they login, you can use sprintf for that:

<? echo(sprintf("Welcome %s %s", $firstName, $lastName)); ?>
OUTPUTS: Welcome John Smith

I think you get the picture. Well the beauty is that you don't always have to echo (display) what you concatenate, for example if you build SQL queries you can easily gain a bit more editing control using sprintf:

<?php
$tableName = "users";
$userID = 1;
$sql = sprintf("SELECT * FROM $s WHERE id = %d", $tableName, $userID);
echo($sql);
?>
OUTPUTS: SELECT * FROM users WHERE id = 1

Here, let me get crazy for a sec, if you follow along then you're doing great...

<?php
$tableName = "users";
$userID = 1;
$limit = 1;
$sql = sprintf("SELECT %s, %s FROM $s WHERE id = %d LIMIT %d", "username", "email", $tableName, $userID, $limit);
echo($sql);
?>
OUTPUTS: SELECT username, email FROM users WHERE id = 1 LIMIT 1

You can see we used hard coded parameters along with variables. That example was a basic SELECT SQL statement, sprintf will shine with your complex statements also allowing them to be more maintainable code - that's better for all of us in the long run.

When using sprintf with your recordset it's easy.

  1. Say you have a recordset called rsUser, you can drag the recordset fields right into your code view.
    recordset called rsUser
  2. Start typing in the your sprintf code, and drag in some recordset fields; yours might look like this example code:

    <?php
    $welcomeText = sprintf("Welcome %s, your email is %s", $row_rsUser['username'], $row_rsUser['email']);
    echo($welcomeText);
    ?>
    OUTPUTS: Welcome jsmith, your email is johnsmith@aol.com

Venture with sprintf() and the world is yours!

I can't really stress how widely sprintf is used, it's a great built in feature to PHP. You'll see more uses for it once you start thinking about where it'll help make your code possibly more modular, and at a minimum maintainable.

Chris Charlton

Chris CharltonChris, Los Angeles' CSS & ActionScript guru, successfully cannonballed into web development in the late 90's. Always caught up with the latest in Flash, Dreamweaver, Fireworks, and XML, Chris authored premium articles for the largest Dreamweaver/Flash community (www.DMXzone.com) and produced WebDevDesign (iTunes featured), a popular Web Design & Development Podcast. Somewhere, Chris finds time to run an authorized Adobe user group focused around open source and Adobe technologies. Being a big community leader, Chris Charlton remains a resident faculty member of the Rich Media Insitute and lends himself to speak at large industry events, like JobStock, NAB, and FITC Hollywood.

Brain cycles from Chris are always Web Standards, Flash Platform, and accessibility.

See All Postings From Chris Charlton >>

Place your comment about PHP - sprintf (to the finish line)




You must me logged in to write a comment
Comments

Be the first to place a comment