PHP - count li elements inside ul

12,406

Solution 1

You can do a very simple Substring Count for <li> (or -li-) on that string and it would return the number of items.


Edit:

$count = substr_count($html,'<li>'); //where $html holds your piece of HTML.

Solution 2

Assuming this HTML is not output by you (otherwise it should be trivial to count the number of elements), you could use PHP's DOMDocument.

$dom = new DOMDocument;

$dom->loadHTML($str);

foreach($dom->getElementsByTagName('ul') as $ul) {

   $count = $ul->getElementsByTagName('li')->length;

   var_dump($count);

}

CodePad.

This code will count the number of li elements in each ul element. If you don't care about individual ul elements, just use $dom->getElementsByTagName('li')->length.

Solution 3

Your answer lies with DOMDocument.

For example:

$dom = new DOMDocument();
$dom -> loadHTML("<ul><li></li><li></li></ul>");
$li = $dom->getElementsByTagName("li");
foreach ($li as $li_c){
$i++;
}
echo $i;
Share:
12,406
Admin
Author by

Admin

Updated on June 24, 2022

Comments

  • Admin
    Admin almost 2 years

    i'm searching for a way to count dynamic li elements inside an ul in php (not js).

    For example:

    <ul>
    
      <li> lorem </li>
    
      <li> ipsum </li>
    
      <li> dolor </li>
    
      <li> sit </li>
    
    </ul>
    

    would return me the number 4. (am i too stupid to use proper code here?)

    Is there some way to accomplish that in php?

    Thanks in advance!

    EDIT:

    The markup is generated by a cms system, the count should be placed before the list, inside the template file.

  • Savageman
    Savageman over 12 years
    As it's very simple I would even suggest count both. ;)
  • Admin
    Admin over 12 years
    Thanks for the answer. Could you show me a example? I'm not shure how to accomplish that.
  • Admin
    Admin over 12 years
    Thanks again! I need to identify the ul using it's tag ID ('portfolio') how would i do that?
  • thwd
    thwd over 12 years
    you should have written that in your question from the start. Use the other solutions suggested and do your homework.
  • Admin
    Admin over 12 years
    oh, what a nice person you are, tom. I'm a designer, not a developer... i came here to get help, and not some stupid answers