0

I am trying to have the function print the # of sub items in each parent item but can't seem to get that to work. For some reason print_r(count($arr[$key]['children'])) is outputting first, then looping through the rest and putting a number 1 where it is supposed to be returning a count.

function create_list($arr)
{
    $html = "";
    foreach($arr as $key => $value) {
        if(count($value['children']) > 0) {
            $html .= $value['name'].' (' . print_r(count($arr[$key]['children'])) . ')<ul>';

            foreach($value['children'] AS $child) {
                $html .= '  <li><a id="'.$child['menu_item_id'].'">'.$child['name'].'</a></li>';
            }

            $html .= '  </ul>
                        ';
        } else{
            $html .= '  <a class="menuitem" id="'.$value['menu_item_id'].'">'.$value['name'].'</a>';
        }
    }

    return $html;
}

    echo create_list($menu_items);

Outputs the following:

22Main Task (1)
 o second task
 o sub task
George (1)
 o test
 o tester

Where it says 22MainTask, the 22 is the results from the count from each root level item. What is the proper way to return a count on that? I am hoping to be able to also print (2/5) tasks complete type, but if I could at least get it to return an accurate count that would be a great first step.

3
  • 3
    why are you using print_r? why not just count($arr[$key]['children'])? you are already concatenating this within a string so print_r is redundant. Also, print_r (as well as var_dump) output straight to the browser, i.e. bypasses html rendering, so that would be why 22 appears before your html Commented May 5, 2014 at 18:52
  • You should really be using htmlspecialchars() around arbitrary data used in the context of HTML. At best, you're creating invalid HTML once in awhile, and at worse you are open to XSS attacks. Commented May 5, 2014 at 19:18
  • Thanks Celeriko, your way worked also, but I couldn't mark it as correct since it was just a comment. Commented May 5, 2014 at 19:26

1 Answer 1

1

Add a second parameter to return the value instead of printing it immediately.

print_r($data, true)

In your example, it prints a count of "1" because print_r returns true (which is converted to "1") if you don't provide the second parameter as true.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.