PHP HelpPHP Help

Online Community that helps beginners learn PHP,
and webmasters solve PHP coding problems

since 1999





Introduction to PHP Programming

Your first PHP script: Hello World!

The quickest way to learn PHP is to start using it and see what happens. We'll start by diving right into the good old "Hello World" script you may have seen when learning other languages. It simply prints "Hello World" to the browser screen using the echo() function.

Each line of code is requires a semicolon at the end. You will probably forget to add the semicolon from time to time and your script will display a syntax error. They are easy to miss. I still leave them off. If you've used a number of programming languages, they all do not use the semicolon as their end of line terminating character, so it's easy to slip up. I sometimes find myself typing C in Perl or Perl in PHP. Perl syntax is very different from PHP, which is more formal with its C influenced functional syntax. For example in Perl you can pretty much drop a regular expression into a statement anywhere, but in PHP you must explicitly make a function call to a regular expression function (ereg() or the Perl-like preg(). What might be natural for a Perl aficionado to code right into their program without thinking, requires putting the regular expression into a function in PHP.

PHP code is delimited by left < and right > brackets. This gives a one line PHP program the appearance of an HTML tag. One liners are often used for outputing content mixed right into HTML.

<?php echo("Hello World!\n"); ?>

<?php print "Hello World!\n"?>

<?php print "Hello World!<br>"?>
 

Most people favor the print function over echo(), I think for clarity. "echo" is a term that might cause confusion while "print" is obvious.

The echo() function sends one or more strings of text to the browser for display. Actually, echo is not function but a "language construct" but you do not have to worry about that. It acts like a function. But it does mean that you can save some typing. As a result, the parenthesis are not required. Now, lets take a look at some of the typical PHP syntax in the script. The beginning and end of a PHP code section is marked by angle brackets (less than and greater than signs) followed or preceded by a question mark. The end of each line is marked by a semicolon. The "\n" is a special "escape code" meaning print a new line (or "newline") that represents a line break in plain text. This is how you would print text to be displayed in a textarea field. For printing to a web page, you need to specify line break tags as the third example shows. Something more appropriate for the web, which leads us into the next topic.

Pages:  1   2   3   4Next:  Simple Web application in PHP »




Copyright © 2017 PHPHelp.com