Welcome Guest!
Please login or register.

Main

User Info

Welcome, Guest. Please login or register.
September 04, 2010, 07:15:43 PM

Login with username, password and session length

Themes


Site Stats

Members
  • Total Members: 79
  • Latest: tamasir
Stats
  • Total Posts: 306
  • Total Topics: 64
  • Online Today: 7
  • Online Ever: 54
  • (May 24, 2010, 09:32:59 AM)
Users Online
Users: 0
Guests: 7
Total: 7

Author Topic: PHP Lesson -- Arrays  (Read 2525 times)

Offline IchBin™

  • Administrator
  • Full Member
  • *****
  • Posts: 145
PHP Lesson -- Arrays
« on: February 28, 2009, 04:43:30 PM »
What is an Array? -- An array is something that can hold a set of values (strings, numbers etc.) that can all be dynamic.

One way to create an array in PHP:

$myArray 
= array('name' => 'ichbin''my_height' => '6ft''my_weight' => '200lbs');


This means that you can now grab any of those values. For instance, after declaring that array you could echo out this line:

echo 'Hi, my name is '$myArray['name'],'.';
echo 
'I am '$myArray['my_height'],' tall and weigh ',$myArray['my_weight'],'.';


The above would output this:
Hi, my name is ichbin. I am 6ft tall and weigh 200lbs.

There are different types of arrays. The array I posted above is called an associative array. Associative arrays have a key and a value. The key is the first element, and the value is the second element. For example, in 'name' => 'ichbin', name is the key, and ichbin is the value of that key. Indexed arrays do not contain the keys. Well, at least not visibly. Here's an example:

$names = array('fred''barney''jason''jennifer''todd');

Now, you can see that there is no key's given in this type of array. However, if you were to print this array out you would see that this array actually looks like this inside PHP's memory.

$names
[0] => 'fred';
$names[1] => 'barney';
$names[2] => 'jason';
$names[3] => 'jennifer';
$names[4] => 'todd';


So, if you need to access jennifer in the array you would call $names[3]. Take notice that the indexed array starts with a zero. Since it is treated this way, you might find yourself thinking that you need to print the 4th element of an array by doing $array[4], when in actuality it is $array[3]. Make sense? :)

There are many things you can do with arrays such as; nesting multiple arrays inside each other, array_pop() to get the last element of an array, array_push() to put an additional element on the end of an array etc. The list goes on, and you can read more about all the different functions at the following link. I'll just cover the basics of the array and let you figure out how to use different array functions. :)
http://us2.php.net/manual/en/book.array.php

Nesting arrays:

$dogs 
= array(
    
'boxer' => array('color' => 'brown''weight' => '60lbs'),
    
'shitzu' => array('color' => 'black''weight' => '15lbs')
);


Now you can get any of the attributes by drilling down the array. For instance you can get the color of the shitzu by echoing out $dogs['shitzu']['color']. Pretty cool eh? Some syntax you should take notice of.  First, notice the => assigns an additional array for each dog. This is how the nesting happens. Also, take notice that after the first nested array there is a comma. This tells PHP that additional arrays/elements are still coming. The last row in the array does not require a comma as you can see.

There are so many ways you can use arrays. To give a final example, I'll show how you can pull the data from an SQL table and throw it into an array. Lets pretend we have a users table called members, and in that table you have rows for id, name, city, state, register_date. Read the comments in the following code to understand how it works.

Code: [Select]
// Include our Database class to connect to the DB
include('incs/db_class.php');

// The query to select everything from the members table
// This query assumes you have a row with the column 'id' that equals 1
$query = 'SELECT * FROM members WHERE id = 1 LIMIT 1';

// Run the query and assign it to $result
$result = mysql_query($query, $database->connection);

// Declare the array, otherwise PHP will say WTF?
$userArray = array();

// Now lets go through the $row array that is automagically created by the
// mysql_fetch_assoc function and assign the values to our $userArray. :)
while ($row = mysql_fetch_assoc($result))
{
// This adds each $row[] to our $userArray
$userArray += $row;
}

To see the results of the above code you can print_r() the $userArray at the end. print_r is a great function for troubleshooting arrays when they aren't working as you may expect. I usually < pre > the output to see it printed in a nice format like this:
echo '<pre>'print_r($userArray),'</pre>';

It would then show you this:
Array
(
    [id] => 3
    [name] =>
    [city] => Las Vegas
    [state] => Nevada
    [register_date] => 9123879234
)

As you learn to code you will discover how much print_r can be your friend. :D I have only just scratched the surface on using arrays, but I think that's about it for now. Any questions feel free post them.
« Last Edit: February 28, 2009, 04:50:11 PM by IchBin™ »
Signatures Go here!!

Offline Ianedres

  • Jr. Member
  • **
  • Posts: 29
Re: PHP Lesson -- Arrays
« Reply #1 on: March 10, 2009, 08:00:37 PM »
Good tutorial Ich. Been busy and got a few minutes free to drop in...

Arrays can reduce so much of your workload, once you utilize the elements properly, especially when reading in information from a file or other types of lists.

The looping of the foreach statement truly shows the power in generating tables of the information quickly and uniformly.

Also available is the sort (and its variants such as ksort, usort, rsort, etc) function, which can organize your array in various ways.

Once I grasped the purpose of arrays, my scripts were greatly reduced in size and easier to understand when debugging and modifying. Once you create the array's method of getting the elements stored, you can manipulate the array in so many ways and create versatile output methods quickly.

$foo++;