Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

jason chan
jason chan
31,009 Points

foreach I don't understand the code

<?php
$social_icons = array('twitter', 'instagram', 'google');
?>
<section class="sidebar text-center">
      <div class="avatar">
        <img src="img/avatar.png" alt="<?php echo $name ?>">
      </div>
      <h1><?php echo $name ?></h1>
      <p><?php echo $location ?></p>
      <hr />
      <p><?php echo $info ?></p>
      <hr />
      <ul class="social">
        <?php 
        foreach($social_icons as $icon){        
        ?>
        <li><a href=""><span class="icon <?php echo $icon ?>"></span></a></li>
        <?php
        }
        ?>
      </ul>
    </section>

I don't know why the list gets printed out three times without echo.

1 Answer

Sean Do
Sean Do
11,933 Points

foreach is a loop, it runs the code line by line until it reaches to the end of its {}. Then it shoots back up, repeating the process. while iterating the arrays.

Does that make sense?

Honestly, you can change it to have the echo, if you like?

<?php 
foreach($social_icons as $icon){        
    echo "<li><a href=''><span class='icon " . $icon . "'></span></a></li>"
}
?>
jason chan
jason chan
31,009 Points

Thanks man that would make a lot more sense.