PHP printing - How to print variables in a PHP string

Nothing major here, just a quick example of how to print variables in PHP, particularly how to print variables in the middle of a PHP string. When you first get started programming in PHP, how to print variables in a PHP string is a common question, so I thought I'd share some examples here.

There are many ways to print variables in a PHP string, but these are some of the most common approaches:

<?php

$count = 10;
// a simple php print syntax
print "(1) Count = $count.\n";

// php print syntax with parentheses
print("(2) Count = $count.\n");

// the php printf function
printf ("(3) Count = %s.\n", $count);

?>

Besides these approaches to print variables in a PHP string, you can also use the PHP echo function instead of the print function, but the function you choose is up to you, and frankly, it doesn't make any difference, other than which print function you prefer, or which function your team/project has agreed to use.

Of course if you need to print formatted variables in a PHP string you'll want to go with printf, or perhaps sprintf, but for other PHP variable printing needs, echo and print are just fine.

As a final note, if you're new to the printf method, this page on A printf format reference page (cheat sheet) and this page on Perl printf examples (printf formatting examples) may be helpful.