Reputation: 1094
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];
}
}
?>
Upvotes: 0
Views: 102
Reputation: 147146
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];
Upvotes: 1
Reputation: 18557
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.
Upvotes: 1