Jump to content

need some help with my PHP :(


OrganizedFellow
 Share

Recommended Posts

Can I get some help with my terrible PHP logic?

I am attempting to generate alternating CSS classes, even and odd. So I wrote this little function:

function doAlt($n) {
	if ($n % 2) {
		echo('odd');
	}else{
		echo('even');
	}
}

I figured how to output like this:

for ($i = 0; $i <= 10; $i++)  {
	echo doAlt($i).$i."<br>";
}

Resulting HTML is this:

even0
odd1
even2
odd3
even4
odd5
even6
odd7
even8
odd9
even10

So far, so good!

Here is where I inserted it into my code:

<section>
	<ul>
	<?php
		$blogpages = $pages->get("/blog/");
		$children = $blogpages->children;
		$children->prepend($blogpages);
		foreach($children as $child) {
			// my function to print even or odd for alternating CSS classes
			for($i=0;$i<=10;$i++){
				echo "<li>";
				echo "<h3>{$child->title}</h3> \n";
				echo doAlt($i).$i;
				echo "{$child->snippet} \n";
				echo "</li> \n";
			}
		}
	?>
	</ul>
</section>

The resulting HTML is each blog entry repeating multiple times, in this case $i=<10, so ten times.

I did it like that to see how it would print/echo out before I stuck it in my CSS.

How can I give each entry a different CSS class?

Link to comment
Share on other sites

Like this ?

<section>
    <ul>
    <?php
        $blogpages = $pages->get("/blog/");
        $children = $blogpages->children;
        $children->prepend($blogpages);
        $i = 0;
        foreach($children as $child) {
            // my function to print even or odd for alternating CSS classes
            echo "<li>";
            echo "<h3>{$child->title}</h3> \n";
            // echo doAlt($i).$i; // Insert your class here using doAlt
            echo "{$child->snippet} \n";
            echo "</li> \n";
            $i++;
        }
    ?>
    </ul>
</section>
 
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...