-1

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>
JZeig1
  • 403
  • 1
  • 6
  • 13
  • 1
    You have an extra level of array (i.e. too many `[`) in `$data = [ ['nameID'=> '1` - `$data = ['nameID'=> '1` – Nigel Ren Apr 21 '19 at 14:07

1 Answers1

1

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>
yuko
  • 325
  • 1
  • 8
  • I add this foreach to see if it would work inserted into the table after table tag and this after the last b4 – JZeig1 Apr 22 '19 at 00:52
  • any ideas why I'm getting Illegal string offset. It's also returning the first letter of each variables data value – JZeig1 Apr 22 '19 at 01:01
  • I have a slight difficulty in understanding exactly what you mean, is it possible you could add it to your question with the full code, or ask a new question with the link here? – yuko Apr 22 '19 at 12:33
  • Thanks for all your help. I've added the steps I'm taking to increase my understanding of arrays. Appreciate you... – JZeig1 Apr 22 '19 at 14:17