Search the Site

Sponsors

bottom corner

How to output a string in PHP

This article will show the steps to perform the basic "hello world" exercise in PHP.

This page is filed under keyword(s): php.

In PHP, to output a line, we can use either the echo() or print() functions. All six examples below have the same output of "hello world":

echo('hello world');
print('hello world');
print 'hello world';

echo("hello world");
print("hello world");
print "hello world";

Note the print() function can work without parenthesis. That is because print() is not really a function; print() is actually a language construct. Functions print() and echo() pretty much do the same thing, so generally you can use whichever one you prefer, though echo() actually gets processed faster, so if you are working with a larger application, this may be something to keep in mind.

To output a string variable, we can do something like this:

$name = "world";

echo('hello '.$name);
print('hello '.$name);
print 'hello '.$name;

echo("hello ".$name);
print("hello ".$name);
print "hello ".$name;

echo("hello $name");
print("hello $name");
print "hello $name";

Once again, all examples above output "hello world", and the character used to concatenate the "hello" and the variable that contains "world" is the period character; the period is equivalent to the ampersand sign in VB/ASP and the plus sign in Java/JSP. Now, see the third set above where we used double quotes to enclose the string and the variable together. This is a special functionality you can use only with double quotes. It is a way to make your coding process slightly simpler, and the resulting code slightly easier to read, but keep in mind that this method makes the code run just a tad bit slower because when the PHP engine sees the double quote, it needs to be prepared to find and process variables -- even if none are found.

In conclusion, echo() and print() are nearly identical, and the usage of double and single quotes are nearly identical, and you may choose whichever one that suits your style better. In terms of optimizing processing speed, however trivial, using echo() with single quote is preferred.

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): php.
Author: C. Peter Chen
Last updated: 20 Jan 2009

bottom corner