c.k c.k - 6 months ago 8
PHP Question

Undefined offset on array - Get they key of each arrays

This is my existing code:

foreach($masterData as $data) { ?>
<tr>
<td><?=$data[0]?></td> //error line here
</tr>

<?
echo '<pre>',print_r($data),'</pre>';

}?>


Result when try printing the
$data
:

Array
(
[payment] => Array
(
[name] => name
[email] => address
[depositdate] => 3-mar-16
[depositamount] => 200

)

)
1
Array
(
[payment] => Array
(
[name] => John
[email] => sample@yahoo.com
[depositdate] => 29-Apr-16
[depositamount] => 5000.70

)

)
1


But echoing the
$data[0], [1], [2]
.. PHP give me notice:
Notice: Undefined offset: 0


Possible cause of this error? Anything wrong with my code and how to fix it?

Answer

Try this to get key of all index in array:

<?php 
foreach($masterData as $key=>$data) { // you can get key of array in $key
?>

<tr>
       <td><?=$key?></td> <!-- you can get $key here -->
</tr>

<?php
echo '<pre>',print_r($data),'</pre>';
}
?>