php 101

Variables

Now you've got a basic PHP document set up, but it doesn't do anything interesting. You could have just put "Hello World!" directly in HTML. Let's try something else.

In this example, $yourname is a "variable" - a placeholder unit that can store all kinds of information. The echo statement substitutes the variable placeholder with the value of that variable. In PHP, all variables start with a $ character.

This example still isn't terribly interesting - you still could have done this in straight HTML. The power of variables becomes clear when you think about all of the places that variable data can come from. $yourname could be pulled from a database after you log into a site. It could be pulled from a parameter in the URL. It could be extracted from a form field submitted by the user on the previous page. It could be pulled from a cookie on the user's hard drive. The possibilities for interactivity are endless.

So what if you did want to pull $yourname from the URL? Easy. URLs often have a series of "parameters" on the end, with "name/value" pairs like this:

http://example.com/phptest/hello.php?yourname=Joe&yourage=32

The portion after the ? marks the beginning of the parameters, which are separated by & symbols. Ever notice how you can bookmark the URL of a page of Google search results and bring it up later without re-typing your search query? That's because the search terms are stored as parameters in the URL. This is a very common practice in web development. You can access URL parameters in PHP with the global $_REQUEST variable, which gives you access to information in the browser's request from the server. Modify your code so it looks like this:

Now refresh the page in the browser. It should read:

Hello Joe! I see that you're 32 years old.

Voila! Instant dynamic web page.

So what's with the echo(); business we've been using? echo() is an example of a "function" - a command that does something to something else. Virtually all programming languages have them. Hundreds of functions come with PHP, and you can use them whenever you need them. You can also write your own functions to perform custom operations. We'll be doing that later in this tutorial.

A function takes zero or more "arguments," which tell the function what to act to on and/or how to act on it. In this example, echo() takes a single argument -- a string to print back to the screen. "Hello world!" is an argument to the echo() function. We'll explore functions more thoroughly in a bit - for now, just remember that a pair of parentheses follow a function call, and that arguments to the function go inside the parentheses.