Search:

Home | Programming | Php


Taking Advantage of Arrays

By: Deceth

Last week we started exploring the very basics of PHP programming. We started by first discussing the Web Server/Browser relationship, then began looking at PHP by first introducing how to comment our PHP code which is very important. We then introduced the echo and print functions, and demonstrated how to use variables and the variable naming rules. We also showed how to use concatenation.

The next step in our quest to conquer PHP is to explore arrays which are similar to variables. Arrays are used when you would like to create many variables which will be similar. Rather than create hundreds of variables, a single array could be used to store all of the related values. Each element in the array will have its own ID number which you can then use to find the desired value. For example:

<?php
$website[0] = "www.webdevnotes.com";
$website[1] = "www.looble.com";
$website[2] = "www.battlecity.net";
?>


As you can see above, rather than create three different variables each containing the website URL, we instead created a single website array and stored the different website URL's in the array. You may be asking yourself now, what is the difference between using an array like this and just using different variables? Is it just used to make the code more neat and organized? Actually, while using arrays do make the code more organized as they associate related data together, the real advantage will come when you start using loops. I'll talk more about loops later this week.

Also, one thing to note about arrays is that it is not actually necessary to store data in an ordered fashion or to even use numerical values at all. In the above example I stored the URL's in $website[0], $website[1], and $website[2]. You will find in many cases storing things in such a manner will be beneficial, especially when using loops. However, really, you can think of the locations where the data is saved as buckets which you can give any name you like. For example:

<?php
$luckyNumber["Deceth"] = 11;
$luckyNumber["Bob"] = 67;
$luckyNumber["Harold"] = 99;
?>


Below is an example of using the above array to print Bob's lucky number to the screen:

<?php
print "Bob's lucky number is " . $luckyNumber["Bob"];
?>

Article Source: http://www.writerdatabase.com

www.webdevnotes.com/taking-advantage-of-arrays/

Please Rate this Article

 

Not yet Rated

Click the XML Icon Above to Receive PHP Articles Via RSS!

Powered by Article Dashboard