Using arrays in PHP can be a very powerful technique of handling data.
If you are not familiar with arrays in PHP then use simple code!
Example of simple code.
$fruit['apples'] = 'I like apples';
$fruit['oranges'] = 'I like oranges';
$fruit['banana'] = 'I like bananas';
Example of advanced code.
$fruit = array("apples" => 'I like apples', "oranges" => 'I like oranges', "banana" => 'I like bananas');
Using advanced code saves lines in the source code but if you are not familiar with arrays it could be harder to troubleshoot if you get parse errors. Once you feel confident with arrays then I would recommend using advanced code.
Reading from arrays.
Arrays are very simple to read from. Using our example code above, to see the value of Apples we would use
echo $fruit['apples'];
this would return: I like apples
Looping through arrays
Looping through arrays is easy too, but this is where people usually get stuck. Just look at it from a logical point of view. We are going to use the foreach function to go through the array.
foreach($fruit as $key => $value) {
echo $key . ' : ' . $value . '<br />';
}
This would return:
apples : I like apples
oranges: I like oranges
banana: I like bananas
Using the foreach function above, think of $key as the name and $value as the information we assigned.
If you would like any more information regarding arrays then please leave a comment or visit the PHP manual by clicking here
#1 by roger on March 11th, 2009
I need a tutorial on how to load a query result into an 2 dimensional associative array. For example the result set contains:
Name Sales Goal Sales
John Smith $100000 $120000
Richard Roe $100000 $95000
Donna Doe $120000 $210000
Patty Poe $80000 $65000
The array is [0][Name],[0][Sales Goal],[0][Sales]
Where:
[0][Name]=John Smith
[0][Sales Goal]=$100000
[0][Sales]=$120000
[1][Name]=Richard Roe
etc…
#2 by Colin Jensen on March 11th, 2009
Hello Roger,
Thank you for leaving a comment.
$h = mysql_query(”SELECT * FROM `names`”);
if(mysql_num_rows($h)) { // Check we have results
while($row = mysql_fetch_assoc($h)) { // Start a loop through them all
$myarray[$row['ID']]['name'] = $row['name'];
$myarray[$row['ID']]['age'] = $row['age'];
}
}
I hope this helps you Roger, let me know