Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

jason chan
jason chan
31,008 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,008 Points

Thanks man that would make a lot more sense.