Posted on Tuesday, November 17, 2009 at 10:47 AM
In my last post I discussed associative arrays. Because the keys are not numeric it can be tricky to loop through them unless you use the foreach command. The foreach command will return each key value pair of an associative array like so:
foreach($myArray as $key => $value) {
echo "This is the key: $key. This is the value: $value<br>";
}
Now you can really harness the power of associative arrays in php!
Posted on Tuesday, November 17, 2009 at 10:45 AM
Associative arrays in php are very useful. You can store something in an array as a key value pair so that you can lookup a piece of data quickly based on its key. For instance if i have an array
$groceries = array();
I can set a key called "fruit" and set its value to "banana" like so:
$groceries['fruit'] = 'banana';
Now when you print out the value of $groceries['fruit'] (via echo) you will get the output banana.
I have used associative arrays to store the anchor text of links. For instance, on a site you might do
$aLinkKey = 'tropical fish';
$links[$aLinkKey] = 'http://www.tropicalfishkeeping.com'
and when you echo <a href="{$links[$aLinkKey]}">$aLinkKey</a> you get
tropical fish
Associative arrays are simple to use. As you keep going you will find that they are really one of the backbones of php. Next time we will discuss how to loop through them.
Posted on Tuesday, November 17, 2009 at 10:37 AM
The first thing I taught myself to use in PHP is the PHP include statement. The PHP include statement is powerful because you can include one file, for instance a header file, in other files. Using PHP include statements, you can create a header file for your site and simply include it in other files rather than copying and pasting the code that comprises your header in each file. You can use the PHP include statement like this:
include 'myHeader.php';
or
include("myHeader.php");
either one will work. you can also use include_once if you have any defines (more on that later) in your include file, but if it is simply a HTML header you shouldn't need to worry about it.
I hope this helped!