DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Five Java Books Beginners and Professionals Should Read
  • How Web3 Is Driving Social and Financial Empowerment
  • Turbocharge Ab Initio ETL Pipelines: Simple Tweaks for Maximum Performance Boost
  • Front-End: Cache Strategies You Should Know

Trending

  • Five Java Books Beginners and Professionals Should Read
  • How Web3 Is Driving Social and Financial Empowerment
  • Turbocharge Ab Initio ETL Pipelines: Simple Tweaks for Maximum Performance Boost
  • Front-End: Cache Strategies You Should Know
  1. DZone
  2. Coding
  3. JavaScript
  4. Formatted Strings With PHP

Formatted Strings With PHP

Paul Underwood user avatar by
Paul Underwood
·
Mar. 22, 13 · Interview
Like (0)
Save
Tweet
Share
4.03K Views

Join the DZone community and get the full member experience.

Join For Free

When you are using PHP to putput a string on the page most of the time you will use the syntax echo, which will take the following string and display that string in HTML.

You can even concaternate multiple strings or variables together to be outputted by the echo syntax.

Here is an example of using echo to output multiple options in a select box.

<?php
        $options = array(
                        'option1' => 'title1',
                        'option2' => 'title2',
                        'option3' => 'title3',
                        'option4' => 'title4',
                        'option5' => 'title5'
                        );
        echo '
<select>';
        foreach($options as $key => $val)
        {
            echo '
<option value="'.$key.'">'.$val.'</option>
';
        }
        echo '</selected>';
?>

As you can see from the echo syntax that you can create a HTML element by using PHP. This code uses a concatenated string to insert the variables into the value attribute and a title inside the option tag. This is quite easy to read and is fine to use in normal development but what if you were using this method to display a more complicated element with more attributes such as an image tag.

This will create 5 image tags which will populate the a number of different attributes.

<?php
        $options = array(
                        'image1' => array('class' => 'style', 'alt' => 'Image 1', 'title' => 'Image 1', 'width' => '100', 'height' => '100', 'src' => 'http://www.example.com/image1.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 2', 'title' => 'Image 2', 'width' => '200', 'height' => '200', 'src' => 'http://www.example.com/image2.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 3', 'title' => 'Image 3', 'width' => '300', 'height' => '300', 'src' => 'http://www.example.com/image3.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 4', 'title' => 'Image 4', 'width' => '400', 'height' => '400', 'src' => 'http://www.example.com/image4.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 5', 'title' => 'Image 5', 'width' => '500', 'height' => '500', 'src' => 'http://www.example.com/image5.jpg'),
                        );
        foreach($options as $key => $val)
        {
            echo '<img class="'.$val["class"].'" alt="'.$val["alt"].'" title="'.$val["title"].'" width="'.$val["width"].'" height="'.$val["height"].'" src="'.$val["src"].'" />';
        }
    ?>

This time if you look at the echo syntax to output the image tags it's not very readable and can be hard to work out what we are joining together to create the image tag, especially with the different single and double quotes it becomes really hard to read.

The solution is to PHP built in functions sprintf() and printf() to create a formatted string to output in the HTML.

Both these functions do the same thing but the printf() will echo the string directly and the sprintf() function will return a formatted string.

This is how it will be used to display the image tag.

Printf() Function Displaying Image Tag

<?php
        $options = array(
                        'image1' => array('class' => 'style', 'alt' => 'Image 1', 'title' => 'Image 1', 'width' => '100', 'height' => '100', 'src' => 'http://www.example.com/image1.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 2', 'title' => 'Image 2', 'width' => '200', 'height' => '200', 'src' => 'http://www.example.com/image2.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 3', 'title' => 'Image 3', 'width' => '300', 'height' => '300', 'src' => 'http://www.example.com/image3.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 4', 'title' => 'Image 4', 'width' => '400', 'height' => '400', 'src' => 'http://www.example.com/image4.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 5', 'title' => 'Image 5', 'width' => '500', 'height' => '500', 'src' => 'http://www.example.com/image5.jpg'),
                        );
        foreach($options as $key => $val)
        {
            printf('<img class="%s" alt="%s" title="%s" width="%s" height="%s" src="%s" />',
                    $val["class"],
                    $val["alt"],
                    $val["title"],
                    $val["width"],
                    $val["height"],
                    $val["src"]);
        }
    ?>

Sprintf() Function Displaying Image Tag

<?php
        $options = array(
                        'image1' => array('class' => 'style', 'alt' => 'Image 1', 'title' => 'Image 1', 'width' => '100', 'height' => '100', 'src' => 'http://www.example.com/image1.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 2', 'title' => 'Image 2', 'width' => '200', 'height' => '200', 'src' => 'http://www.example.com/image2.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 3', 'title' => 'Image 3', 'width' => '300', 'height' => '300', 'src' => 'http://www.example.com/image3.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 4', 'title' => 'Image 4', 'width' => '400', 'height' => '400', 'src' => 'http://www.example.com/image4.jpg'),
                        'image1' => array('class' => 'style', 'alt' => 'Image 5', 'title' => 'Image 5', 'width' => '500', 'height' => '500', 'src' => 'http://www.example.com/image5.jpg'),
                        );
        foreach($options as $key => $val)
        {
            $image = sprintf('<img class="%s" alt="%s" title="%s" width="%s" height="%s" src="%s" />',
                    $val["class"],
                    $val["alt"],
                    $val["title"],
                    $val["width"],
                    $val["height"],
                    $val["src"]);
            echo $image;
        }
    ?>

As you can see using the printf() and sprintf() functions allows you to much more readable code for outputting formatted strings.



PHP Strings

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Five Java Books Beginners and Professionals Should Read
  • How Web3 Is Driving Social and Financial Empowerment
  • Turbocharge Ab Initio ETL Pipelines: Simple Tweaks for Maximum Performance Boost
  • Front-End: Cache Strategies You Should Know

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: