0

I have multidimensional array with user values I am using for loop to echo those values but I am getting error undefined offset ,here is my code I am not able to understand how to echo those values.

$user_list=array();  //values stored from table in multidimensional array
echo '<pre>';print_r($user_list);

    Array
    (
        [0] => Array
            (
                [id] => 1
                [name] => abc
                [email] => [email protected]
            )

        [1] => Array
            (
               [id] => 2
                [name] => xyz
                [email] => [email protected]
            )

        [2] => Array
            (
               [id] => 3
                [name] => mym
                [email] => [email protected]
            )


    )

<?php 
     for($row = 0; $row <count($user_list) ; $row++){
          echo $row."<br>";
           for ($col = 0; $col < count($user_list[$row]); $col++) {
          echo $user_list[$row][$col];
  }

}
?>
1

2 Answers 2

1

Your problem is that $user_list[$row] is not numerically indexed, it is an associative array (with keys id, name and email). So this loop:

for ($col = 0; $col < count($user_list[$row]); $col++) {
    echo $user_list[$row][$col];

will not work (and gives you undefined offset errors). You should probably use a foreach loop instead:

foreach ($user_list[$row] as $value) {
    echo $value;

Alternatively you could use array_values to get the values numerically indexed:

for ($col = 0; $col < count($user_list[$row]); $col++) {
    echo array_values($user_list[$row])[$col];

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

Comments

1

Your inner loop in expecting index as a number but your inner index is a string. So foreach will be better alternative for you to achieve.

for ($row = 0; $row < count($user_list); $row++) {
    foreach ($user_list[$row] as $col => $val) {
        echo $user_list[$row][$col].' '; // or echo $val directly
    }
    echo "<br>";
}

Demo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.