phparraysloopsmultidimensional-array

How to loop through a multidimensional array


I have the following PHP array structure:

$set = array();
$set[] = array(
    'firstname' => 'firstname 1',
    'lastname' => 'lastname 1',
    "bio" => array(
        'paragraph 1 of the bio,
        'paragraph 2 of the bio',
        'paragraph 3 of the bio'
    ),
);

I then access the array with the following:

<?php $counter = 0;
while ($counter < 1) :  //1 for now
    $item = $set[$counter]?>  
    <h1><?php echo $item['firstname'] ?></h1>
    <h1><?php echo $item['lastname'] ?></h1>
<?php endwhile; ?>

I'm uncertain how I can loop through the "bio" part of the array and echo each paragraph.

So as a final output, I should have two h1s (first and last name) and three paragraphs (the bio).

How can I go about doing this?


Solution

  • You don't need to use a manual counter, you can use foreach. It's generally the easiest way and prevents off-by-one errors.

    Then you need a second inner loop to loop through the bio.

    <?php foreach ($set as $item): ?>  
        <h1><?php echo $item['firstname'] ?></h1>
        <h1><?php echo $item['lastname'] ?></h1>
        <?php foreach ($item['bio'] as $bio): ?>
            <p><?php echo $bio; ?></p>
        <?php endforeach; ?>
    <?php endforeach; ?>
    

    On a related note; you probably want to look into escaping your output.