Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Abe Layee
Abe Layee
8,378 Points

php looping through two dimensional array using for loop

I am trying to loop through my array and display the user name and password for each person, but i keep getting undefined offset

<?php
 $getUserName = $_POST['userName'];
 $getUserPassword = $_POST['pass_word'];
 //echo "user name: " .$getUserName. " <br>" . "password " . $getUserPassword;
 $array = array(
     0 => array (
          'name' => 'Ellie',
          'password'=> 'tr89ial'
     ),
     1 => array(
         'name' => 'greatGuy',
         'password'=> 'abc123'
     ),

     2 => array (
         'name' => 'blogger',
          'password' => '23seventeen23'
     )
 );
$arrayLength = count($array);
for ($i = 0; $i <=$arrayLength; $i++) {
    for ($k =0; $k<=$i; $k++) {

    }
   echo $array[$i][$k];
}
?>

4 Answers

In your second loop:

for ($k =0; $k<=$i; $k++) {

it does not make sense to compare $k directly to $i. You want to compare $k to the size of the $array at $i so:

for ($k = 0; $ <= count($array[$i]); $k++) {

Abe Layee
Abe Layee
8,378 Points

i changed it but nothing is printing out on the screen

Oh yeah... sorry... My PHP skills are a little rusty but I got a REPL up and running and hashed this out for you...

The issue is that PHP stores arrays a little differently than most people would expect. The "echo $array[$i][$k]" doesn't work because PHP isn't storing your values with keys 0 and 1. It is storing them with keys 'name' and 'password'. The array values at keys 0 and 1 are actually undefined. PHP has a foreach loop (http://php.net/manual/en/control-structures.foreach.php) to handle arrays with non-numeric indexes:

<?php
 $getUserName = $_POST['userName'];
 $getUserPassword = $_POST['pass_word'];
 //echo "user name: " .$getUserName. " <br>" . "password " . $getUserPassword;
 $array = array(
     0 => array (
          'name' => 'Ellie',
          'password'=> 'tr89ial'
     ),
     1 => array(
         'name' => 'greatGuy',
         'password'=> 'abc123'
     ),

     2 => array (
         'name' => 'blogger',
          'password' => '23seventeen23'
     )
 );
$arrayLength = count($array);
for ($i = 0; $i < $arrayLength; $i++) {
    foreach($array[$i] as $value) {
        echo $value;
    }
}
?>