To really go all the way with PHP you have to understand arrays. An array is basically a container that groups values together.
Let’s say we want to keep track of my measurements, my bust, waist, and hips. In this not-so-hypothetical example, we could create some variables, $bust = 32, $waist = 24, and $hips = $32. That’s not too bad, but what if we started adding more things, like my height, weight, eye color, hair color, and shoe size (creeps). That’s a lot of variables to keep track of. That’s where arrays come in.
Bust open your helloworld.php. Let’s make an array of my babe. My bust, waist, and hips.
$babe = array(32, 24, 32);
Setting $babe creates the array. Now we can access parts of the array, basically pulling out whatever we need, like this:
print(‘bust: ’ . $babe[0]); print(waist: ’ . $babe[1]); print(‘hips: ’ . $babe[2]);
If we wanted to add my height, in inches, we could do:
$babe[] = 70;
The empty brackets mean that 70 will be added to the end of the array.
We can access it the same way:
print(‘height: ’ . $babe[3]);
The array we defined previously is actually a shortcut for:
array( 0 => 32, 1 => 24, 2 => 32, )
If we leave out the keys, then PHP will automatically create numeric keys, starting at 0.
This is working well, but it’s going to get difficult to remember what value is in what position.
Another way we could have done it is to use strings as keys instead.
$babe = array(‘bust’ => 32, ‘waist’ => 24, ‘hips’ => 32);
This makes things easier to read, and you don’t have to remember if bust is the first item in the array, or if it was hips. The same code above would look like:
print(‘bust: ’ . $babe[‘bust’]); print(waist: ’ . $babe[‘waist’]); print(‘hips: ’ . $babe[‘hips’]);
We could add my height to the array like so:
$babe[‘height’] = 70;
Then access it just like the others:
print(‘height: ’ . $babe[‘height’]);
Arrays can use strings or numbers as keys, and anything as the value, even other arrays.
We could add my eye color:
$babe[‘eye color’] = ‘black’;
Or we could add the types of modeling I do:
$babe[‘modeling’] = array(‘fashion’, ‘lingerie’, ‘swimwear’);
Then we could access the first type of modeling I do like this:
print(‘models: ’ . $babe[‘modeling’][0]);
Now you know your way around arrays and we’re halfway through getting freaky with PHP.
Questions or Comments?