Posts Tagged easy array

Tutorial – How to use arrays in php

1
Digg me

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

  • Share/Bookmark

, , , , , , , , ,

2 Comments