Search code examples
phparraysindex-error

Why am I getting undefined index message


I've setup an array(simple), but when I try to echo back in table, I get the all-too-famous

"Notice: Undefined index: xxxx in line...".

I've tried to change the syntax using different combinations of ' and ", also used ( instead of ['s. None seem to work.

Document: example_1.php

  <?php $data = [
     ['nameID'=> '1','salutation'=> 'Mr','firstName'=> 
     'John','lastName'=> 'Smith'],
    ];
  ?>

    <table>
         <tr> 
            <td> <?php echo $data["nameID"]; ?> </td>
            <td> <?php echo $data["salutation"]; ?> </td>
            <td> <?php echo $data["firstName"]; ?> </td>
            <td> <?php echo $data["lastName"]; ?> </td>         
         </tr>      
    </table>

Just was trying to see if I could get the list items to show up in a table. There's no css setup or anything formating added to the code


Now for the next stage I was trying to setup an 'foreach' loop in order to extract other items added to array. I've done a little research and I've found out that what I'm trying to do is extract from a nested array (without or with list) Here's my code:

<body>

  <table> 
    <?php foreach($data as $data) { ?>
    <tr> 
        <td> <?php echo $data["nameID"]; ?> </td>
        <td> <?php echo $data["salutation"]; ?> </td>
        <td> <?php echo $data["firstName"]; ?> </td>
        <td> <?php echo $data["lastName"]; ?> </td>         
    </tr>
    <?php } ?>


  </table>  

 </body>

Solution

  • You have used [ and ] two times when declaring the array. Try this:

    <?php 
        $data = ['nameID'=> '1','salutation'=> 'Mr','firstName'=> 'John','lastName'=> 'Smith']; 
    ?>
    
    <table>
         <tr> 
            <td> <?php echo $data["nameID"]; ?> </td>
            <td> <?php echo $data["salutation"]; ?> </td>
            <td> <?php echo $data["firstName"]; ?> </td>
            <td> <?php echo $data["lastName"]; ?> </td>         
         </tr>      
    </table>