1

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?

1
  • FYI you are missing a single quote in your bio initialization Commented Dec 11, 2012 at 17:14

4 Answers 4

3

Use foreach loop

foreach($item['bio'] as $listitem) {
   echo $listitem;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

Add into the while loop also this:

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

Note that used coding style is not optimal.

Comments

0

Try:

foreach($set as $listitem) {
if(is_array($listitem)) {
 foreach($listitem as $v) //as $set['bio'] is an array
  echo '<h1>' .$v . '</h1>';
} else  
 echo '<p>'.$listitem.'</p>';
} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.