ptg16476052
656 LESSON 24: Taking Advantage of the Server
One thing you should notice here is that you don’t have to indicate what kind of item
you’ll be storing in a variable when you declare it. You can put a string in it, as I did
when I assigned "red" to $color. You can put a number in it, as I did with $last_
published_at. I know that the number is a timestamp, but as far as PHP is 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() func-
tion. 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.
If you get a warning about not setting a time zone when you
enter the previous date() line, you should add a line setting
your time zone above it in the script: date_default_timezone_
set('America/Los_Angeles'). Change the “America/Los
Angeles” to your time zone. You can find a list of supported time
zones at http://php.net/manual/en/timezones.php.
TIP
Despite the fact that variables don’t have to be declared as being associated with a par-
ticular 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
All the variables you’ve seen so far in this lesson have 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