I am trying to make dynamic function where user can create list without adding <ul> <li>
tag.
here is my function
function the_main_nav($navlinks){
echo '<nav>';
echo '<ul>';
$menuitem = $navlinks;
$pieces = explode(",",$menuitem);
$i=$navlinks;
while($i==','){
echo '<li>' . $pieces[$i] . '</li>';
$i++;
}
echo '</ul>';
echo '</nav>';
}
This is my template tag the_main_nav('1,2,3,44 5');
But its going into endless loop with error. I want auto generate <li>
after each ','
commma. Also if possible I want anchor link within the list so it can be linked with the page.
Instead of while
loop, use foreach
:
foreach ( $pieces as $piece ) {
echo '<li>' . $piece . '</li>';
}
Yep, using a foreach can be cool, but your error is in your logical view. If I look at your algorithm I see : Write some open tags store my argument into a new variable called $menuitem create an array from $menuitem each time you find a "," and store it in $pieces store my argument into a new variable called $i now while $i is equal to the char "," (which is allways false) write my subtags
after that write end tags.
You do not course your array. A foreach loop will do it. But to correct your code you must understand that $i must take as value the indexes of the array, so 0,1,2,3...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.