Output a Multidimensional Array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
monkey64
Forum Newbie
Posts: 1
Joined: Sat Jun 13, 2009 2:06 am

Output a Multidimensional Array

Post by monkey64 »

Hi there. I'm a newbie and I'm learning about multidimensional arrays.
Below is some code which creates an array called $myarray.
My aim is to output the following:

The value of myarray1 is:
ACC201
ACC202
ACC203

The value of myarray2 is:
BBA201
BBA202
BBA203
BBA204
BBA205

Question is how? I've experimented with various nested foreach loops, but I'm just getting tripped up. Can anyone help me?

Code: Select all

 
<?php
 
// Test array
  
$myarray [1][1]= "ACC201";
$myarray [1][2]= "ACC202";
$myarray [1][3]= "ACC203";
 
$myarray [2][1]= "BBA201";
$myarray [2][2]= "BBA202";
$myarray [2][3]= "BBA203"; 
$myarray [2][4]= "BBA204";
$myarray [2][5]= "BBA205"; 
  
foreach($myarray as $key=>$value) {
    echo "The value is $value<br />";
  }
 
?>
globezone
Forum Newbie
Posts: 7
Joined: Wed Jun 10, 2009 4:57 am

Re: Output a Multidimensional Array

Post by globezone »

1) http://php.net/manual/en/book.array.php

2)

Code: Select all

 
// Test array
 
$myarray [0][0]= "ACC201";
$myarray [0][1]= "ACC202";
$myarray [0][2]= "ACC203";
 
$myarray [1][0]= "BBA201";
$myarray [1][1]= "BBA202";
$myarray [1][2]= "BBA203";
$myarray [1][3]= "BBA204";
$myarray [1][4]= "BBA205";
 
 

Code: Select all

 
 
 
foreach ($myarray AS $k=>$v)
{
    foreach ($myarray[$k] AS $p=>$q)
    {
        echo $myarray[$k][$p];
        echo "<br />";
    }
}
 
 

Code: Select all

 
 
for($i=0; $i < count($myarray); $i++)
{
    for($j=0; $j < count($myarray[$i]); $j++)
    {
        echo $myarray[$i][$j];
        echo "<br />";
    }
}
 

Code: Select all

 
$i=0;
while($i < count($myarray))
{
    $j=0;
    while($j < count($myarray[$i]))
    {
        echo $myarray[$i][$j];
        echo "<br />";
        $j++;
    }
    $i++;
}
 
Post Reply