We help IT Professionals succeed at work.

PHP Count number of <LI> tags possible?

error77
error77 asked
on
Medium Priority
1,029 Views
Last Modified: 2012-05-12
Hi all,

I have a html list...

echo '<ul>';
echo '<li>One</li>';
echo '<li>Two</li>';
echo '<li>Three</li>';
//Then some dynamic ones...
if ($var == 1) {
echo '<li>Four</li>';
}
if ($var2 == 1) {
echo '<li>Five</li>';
echo '</ul>';

Now...what I need is to be able to count how many <LI> are displayed in php.

What I need to do is to be able to say....

If ($li_count >4) {
echo 'More than 4';
}

Can this be done in php please?

Thanks
Comment
Watch Question

Freelancer
CERTIFIED EXPERT
Top Expert 2010
Commented:
You can do this:


 
<?php
$li_count = 0;
echo '<ul>';
echo '<li>One</li>';
$li_count++;
echo '<li>Two</li>';
$li_ount++;
echo '<li>Three</li>';
$li_ount++;
//Then some dynamic ones...
if ($var == 1) {
echo '<li>Four</li>';
$li_ount++;
}
if ($var2 == 1) {
echo '<li>Five</li>';
$li_Count++;
echo '</ul>';

If ($li_count >4) {
echo 'More than 4';
}
?>

Open in new window


Otherwise you could use javascript, but I would prefer php method.

Cheers

Commented:
I would recomend this

Regards
<?php
$morethan = 0;
echo '<ul>';
echo '<li>One</li>';
echo '<li>Two</li>';
echo '<li>Three</li>';
//Then some dynamic ones...
if ($var == 1) {
	echo '<li>Four</li>';
	$morethan4 = 1;
}
if ($var2 == 1) {
	echo '<li>Five</li>';
	echo '</ul>';
	$morethan4 = 1;

if ($morethan4==1) {
	echo 'More than 4';
}
?>

Open in new window

Commented:
yo can also replace:

if ($morethan4==1) {
      echo 'More than 4';
}

by

if ($var1==1 || $var2==1) { // this already means there is a 4th <li>
      echo 'More than 4';
}