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

Create a function for a foreach and call it like a function.

Right now i have this: <?php foreach ($pagenamelist as $pagenamelink) { echo "<li>"; echo "<a "; echo ($pagename == $pagenamelink['page_name'] ? $on_page : false); echo " href="; echo ($pagenamelink['page_section'] == true ? $sectionLink : false ); echo "/"; echo $pagenamelink['page_name']; echo '/'; echo ' title="'; echo $pagenamelink['pagename_title']; echo '">'; echo $pagenamelink['pagename_title']; echo "</a>"; echo "</li>"; }?>

I would like to know how do you put the code below in a function and call it globally? for example something like:

function makeNav(){ foreach ($pagenamelist as $pagenamelink) { echo "<li>"; echo "<a "; echo ($pagename == $pagenamelink['page_name'] ? $on_page : false); echo " href="; echo ($pagenamelink['page_section'] == true ? $sectionLink : false ); echo "/"; echo $pagenamelink['page_name']; echo '/'; echo ' title="'; echo $pagenamelink['pagename_title']; echo '">'; echo $pagenamelink['pagename_title']; echo "</a>"; echo "</li>"; } }

1 Answer

I think what you've written would achieve what you want to do! In the function you would probably want to write everything nav related to save repeating yourself:

<?php
function writeNav() {
    echo '<nav>';
    foreach($pagenamelist as $pagenamelink) { 
        echo '<a href="$pagenamelink['pagename_link']">$pagenamelink['pagename_title']</a>'
    } 
    echo '</nav>';
}
?>

<html>
<?php writeNav(); ?>
</html>

An alternative is to include a 'header.php' file which you include on every page. In the header file, you can write your navigation fully or create a function to create it - and you would only have to write the code to call the function once.

To call your function 'globally' (from anywhere in your application?) You can include a functions.php file. Common names are utils.php, lib.php, functions.php etc