HTML and CSS Reference
In-Depth Information
concerned, it's just a number. What if I want a date that's formatted to be displayed
rather than stored in seconds so that it can be used in calculations? I can use the PHP
date() function. Here's an example:
$last_published_at = date(“F j, Y, g:i a”);
This code formats the current date so that it looks something like “June 10, 2010, 8:47
pm.” As you can see, I can change what kind of information is stored in a variable with-
out doing anything special. It just works. The only catch is that you have to keep track of
what sort of thing you've stored in a variable when you use it. For more information
about how PHP deals with variable types, see
http://www.php.net/manual/en/language.types.type-juggling.php.
Despite the fact that variables don't have to be declared as being associated with a partic-
ular type, PHP does support various data types, including string, integer, and float (for
numbers with decimal points). Not all variable types work in all contexts. One data type
that requires additional explanation is the array data type.
Arrays
The variables you've seen so far in this lesson have all been used to store single values.
Arrays are data structures that can store multiple values. You can think of them as lists of
values, and those values can be strings, numbers, or even other arrays. To declare an
array, use the built-in array function:
$colors = array('red', 'green', 'blue');
This declaration creates an array with three elements in it. Each element in an array is
numbered, and that number is referred to as the index . For historical reasons, array
indexes start at 0, so for the preceding array, the index of red is 0, the index of green is
1, and the index of blue is 2. You can reference an element of an array using its index,
like this:
$color = $colors[1];
By the same token, you can assign values to specific elements of an array, too, like this:
$colors[2] = 'purple';
You can also use this method to grow an array, as follows:
$colors[3] = 'orange';
What happens if you skip a few elements when you assign an item to an array, as in the
following line?
$colors[8] = 'white';
 
Search WWH ::




Custom Search