Looping through multidimensional arrays

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Hi all,
I have a 2D array, which I am trying to access, but I am having
problems doing this:

If, for instance, I use a nested for loop to go through the values,
using something like

echo "$MyArray[$loop_var_one][$loop_var_two]";
I get the following:

If I do a var_dump($MyArray[$loop_var_one][$loop_var_two])
I get
string(1) "2"
string(1) "0"
string(1) "3"

Now, if I do a count($MyArray[$loop_var_one]);
to see how many array elements are in the 2nd array index (for the
for...loop), I get zero!
Also, if I do the following
$new_array = $MyArray[$loop_var_one];
to try and populate a second array, and then do a var_dump(
$new_array), I get nothing as well.

Can anyone help please?



Re: Looping through multidimensional arrays

 echo "<br><br>";

 $year = array( "january" => array( "1" => "first", "2" => "second", "3" =>
"third" ),
                "february" => array( "26" => "twenty sixth" ),

 $year['january']['23']="some day";

 $aday = $year['february']['26'];
 echo "$aday<br>\n";

 echo "<pre>\n";
 var_dump( $year );
 echo "</pre>\n<br /><br />\n";

 foreach ( $year as $month => $days )
   $cnt = count ( $days );
   echo "count for $month = $cnt<br />\n";
   foreach ( $days as $key => $value )
     echo "$key => $value<br />\n";
   echo "=====<br />\n";

 $new_array = $year["january"];
 echo "<pre>\n";
 var_dump ( $new_array );
 echo "</pre>\n";


Quoted text here. Click to load it

Re: Looping through multidimensional arrays

Quoted text here. Click to load it

Thanks for your help. By the way, I am not using associative arrays,
just indexed arrays.

I am adding to the array by (in a loop) doing something like
$MyArray[$var1][] = $data_I_want_to_insert

So, just using square brackets and indices is the best way for me. Is
there any way
to do this - none of the websites I looked at helped at all.

I'm only using var_dump to check the contents of the array, I'm not
using it to actually display anything meaningful to screen. The reason
is because I am checking to see what is in the array so that when I
write a combo/drop-down box to screen I can append a "SELECTED"
statement into the "option" tag depending on whether it is in the
array or not.



Site Timeline