2-Dimensional Arrays In PHP

Image frame
2-Dimensional Arrays In PHP
Maruf
Oct 7th, 2008
Maruf scribbled this post.

I LOVE arrays. They make life so much easier and efficient. At first they can be quite difficult to get the hang of, but once you capture the basics, everything really does start to make sense. Each time I play with arrays I seem to learn something new.

Here’s just a quick reminder to myself of how a 2-dimensional array works. I’ve seen a lot of examples online, but they mainly only provide examples that show how to create the array, they rarely show how to echo the data out, which can be annoying for a beginner.

So if you wanted to display something like this:

Fish

Salmon £ 9.00
Cod £ 7.00

Soup

Mushroom £ 5.00
Tomato £ 4.00

You’d use code like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?
 
$menus = array
(
'Fish' => array
(
'Salmon' => '9.00',
'Cod' => '7.00',
),
'Soup' => array
(
'Mushroom' => '5.00',
'Tomato' => '4.00',
),
);
 
foreach($menus as $name => $price)
{
echo "<div>";
echo "<div>$name</div>";
 
if(is_array($price))
{
echo "<ul>";
 
foreach($price as $submenuname => $price)
{
echo "<li>$submenuname";
echo " &pound; $price</li>";
}
 
echo "</ul>";
}
echo "</div>";
}
 
?>

Filed away: PHP

feel free to leave a scribble

Name:
Email:
gravatar
Want an image next to your comments?
visit gravatar.com
Message:
Get a free quote