Example 2 - Variables and Arrays
Example 1 was not the most compelling example, but it does illustrate how PHP scripts are constructed. Let's extend Example 1 to read some information about the user's environment and display it in a Web page. We will start out with a quick overview of variables in PHP.
This example introduces some variables to our PHP script. Variables in PHP begin with the $ symbol. PHP uses arrays and variables to store different values. Variables begin with a $ followed by characters, digits, and underscores. Variable names are case sensitive and are assigned with the '= ' operator. Variables are incredibly useful. For example, you may need to keep track of information submitted via a web form or perform calculations on data and store the results.
Here's a simple example:
$name = 'Elijah'; $yearBorn = 1975; $currentYear = 2005;
An array is an ordered collection of values. Each value can be referenced individually using its position in the array. The first element of an array is in position 0 and the second element is in position 1. Creating arrays in PHP can be done in multiple ways, though the following example is one of the simplest.
$cities = array('Beijing','Oaxaca', 'Habana', 'Jakarta');
For example, to access the second element of the $cities array use $cities.
// create the array $cities = array('Beijing','Oaxaca', 'Habana', 'Jakarta'); print $cities;
Arrays can also be created using a key/value pair combination. These are often referred to as associative arrays or hashes. In a hash each value is associated with a unique key. Unlike list arrays that use a number as an index value, associative arrays use any value. The easiest way to comprehend how a hash works is to think of it as a table. In the following table the country name serves to role as key and the city is the value.
<?php // create the array $capitals = array( 'Cambodia' => 'Phnom Penh', 'Lebanon' => 'Beirut', 'Cuba' => 'Habana', 'Indonesia' => 'Jakarta', 'Finland' => 'Helsinki'); print ($capitals['Cambodia']); // displays the string "Phnom Penh" ?>
Additionally, PHP scripts have access to information about your environment. These variables are stored in special hashes called
<HEAD><TITLE> Example 2 </TITLE> </HEAD>
// $_SERVER[HTTP_USER_AGENT] and $_SERVER[REMOTE_ADDR] are two of many environment // variables in PHP. Environment variables store information about // the user's and server's environment print("Hello World<br>"); print("You are using $_SERVER[HTTP_USER_AGENT]<br>"); print("Your Internet address is $_SERVER[REMOTE_ADDR]<br>");
Example 2 uses two specific environment variables,
PHP Manual Pages