10

here is my code: http://www.pcgage.net/code.zip (sorry, pasting the code caused it to really mess up, even using the code container).

Scroll to line: 160 (to 174) - this is the loop in question. i want to make it so this is the even part, and then some code to make an odd part, so the loop repeats in this order. The reason is that i want to change the content of this loop alternately.

I am not a coder, so the best thing you could do is to post up the new code and i'll add it in where you tell me too, otherwise i'll get lost :)

Hope that makes sense, if not you can check an earlier post about this issue that explains why i need this (after finding out that css alone cannot solve my problem): css/php: how to solve this div float problem / odd even loop in array

this is the loop:

} elseif ( ( $findpost->ID ) != $id ) {

// all other posts except the current post

                    $serp_list_li[] = '<div class="serial-contain">

<div class=""><h5><a href="' . get_permalink($findpost->ID) . '" title="' . $findpost->post_title . '">' .  $findpost->post_title . '</a></h5></div>

<div class="text-align">' .  $findpost->post_excerpt . ' </div>

<div class="date"> ' . mysql2date('M jS, Y', $findpost->post_date) . ' at ' . mysql2date('g:ia', $findpost->post_date) . '</div>


<div class="comments"><a href="' . get_permalink($findpost->ID) . '#comments" title="' . $findpost->post_title . '"><b>' .  $findpost->comment_count . ' Comments</b></a></div>


</div>' . "\n";
                } 



else {              
3
  • I'm not sure exactly what you're asking, but I did find your code thanks to your edit of the first post(line 320 or so for some reason in my editor, lot's of extra new lines in your code). I provide two fixes depending on what you're asking, which I'm a little unclear on, but this solution should work unless I've missed a third problem. Commented Sep 10, 2009 at 3:53
  • @scragar, you've helped get further along, but there seems to be a problem, see above. Commented Sep 10, 2009 at 5:02
  • you really should use a template engine! you are messing up code and design Commented Sep 10, 2009 at 11:45

6 Answers 6

41

The three ways are

Modulo

for ($i = 0; $i < 10; $i++)
{
  if ($i % 2 == 0)
  {
    echo "even";
  }
  else
  {
    echo "odd";
  }
}

Flipping boolean value

$even = true;
for ($i = 0; $i < 10; $i++)
{
  if ($even)
  {
    echo "even";
  }
  else
  {
    echo "odd";
  }

  $even = !$even;
}

And mentioned boolean operator

for ($i = 0; $i < 10; $i++)
{
  if ($i & 1 == 0)
  {
    echo "even";
  }
  else
  {
    echo "odd";
  }
}

The most fastest is boolean operator. But the most robust is flipping method if you have very different numbers (like running through ID numbers and some are missing).

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

1 Comment

while i'm sure these will all work, i'm not a programmer, so to mod your code to work in my script, well, i'm clueless. Thanks, though.
9

I haven't looked over the code, but if it's using a variable to count the loop number you can do:

 for($i=0;$i<$blah;$i++)
   if($i&1){
     // ODD
   }else{
     // EVEN
   }

EDIT(1): I looked at the section you are running into, and now I have another problem, I'm unsure how you are judging what should be odd or not, so I propose two answers:

1: odd loop itteration:

   /* Populate the post list array */
// Add here:
   $oddLoop = false;
   foreach ($findposts as $findpost):
//.....
if($oddLoop=!$oddLoop){
  // code for odd loop numbers
}else{
  // code for even loop numbers
}

2: Odd ID number:

 } elseif ( ( $findpost->ID ) != $id ) {
    if($findpost->ID & 1){
       // ODD
    }else{
       //EVEN
    }

5 Comments

wish i was confident enough to try and put this in the right place, but i'm not. I've since put the loop code in the post, hope that can help to show me where to put this, thanks!
i must have counted with some empty lines in there, look for this comment line: // all other posts except the current post it's this loop.
i understand step 2, just not step 1. Let's assume i will replace all from /* Populate the post list array */ to // we have the current post and link is to be shown - for your new code, what would it be then? Sorry, i'm no good with php :(
any help on this one, i feel so close to a solution
option 2 is not working, it only does the first iteration of the array, all others are not alternating
7

For loops increment by 1:

$state = 'odd';  
for (...)
{
   $state = ($state == 'even' ? 'odd' : 'even');
   echo $state . PHP_EOL;
}

Output:

even
odd
even
odd
...

Comments

2

If you ever delete an article you could be in trouble - your code assumes that ID runs (odd,even,odd,even) etc.

A better idea would be to create a separate iterator object to feed you the necessary values at each step. Here's what I use:

class LoopingPropertyIterator implements Iterator
{
    private $startat = 0, $position = 0;
    private $propertylist = array(
        'boolean' => array(false, true),
        'day' => array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
        'dow' => array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')
    );

    public function __construct($args, $startat = 0)
    {
        $this->startat = (int)$startat;
        $this->position = $this->startat;

        foreach ($args as $name => $arr)
            $this->__set($name, $arr);
    }

    public function __get($name)
    {
        if (!array_key_exists($name, $this->propertylist))
            throw new Exception(__METHOD__ . " unknown property $name");

        $t =& $this->propertylist[$name];

        if (is_array($t))
            return $t[$this->position % count($t)];
        else
            return $t;
    }

    public function __set($name, $arr)
    {
        $this->propertylist[$name] = $arr;
    }

    public function current()
    {
        return $this->position;
    }

    public function key()
    {
        return $this->position;
    }

    public function next()
    {
        ++$this->position;
    }

    public function rewind()
    {
        $this->position = $this->startat;
    }

    public function valid()
    {
        return true;
    }
}

then your output simplifies to

$iter = new LoopingPropertyIterator( array(
    'outerclass' => array('serial-contain-right','serial-contain-left'),
    'innerclass' => array('text-align2','text-align')
));

...

elseif ( $findpost->ID != $id ) {
    $link = get_permalink($firstpost->ID);
    $title = $findpost->post_title;
    $datetime = mysql2date('M jS, Y', $findpost->post_date).' at '.mysql2date('g:ia', $findpost->post_date);

    $serp_list_li[]=
<<<TEXT
    <div class="{$iter.outerclass}">
        <div class="title">
            <h5><a href="{$link}" title="{$title}">{$title}</a></h5>
        </div>
        <div class="{$iter->innerclass}">{$findpost->excerpt}</div>
        <div class="date">{$date}</div>
        <div class="comments">
            <a href="{$link}#comments"> title="{$title}">
                <b>{$findpost->comment_count} Comments</b>
            </a>
        </div>
    </div>
TEXT;

    $iter->next();
}

2 Comments

sounds great, but this has all got to complex for someone who doesn't code (me). Unless i can get the php file update by someone and posted back, i'll never get this to work :(
I patched your file at pastebin.com/m2606fee0 for you - as you can see, it's just a matter of cutting and pasting into the appropriate spots. Hope that helps.
0

Are you sure $findpost->ID contains sequential numbers?

You could replace the if/else with s short ternary statement like this:

$side = empty($side) || $side == 'right' ? 'left' : 'right';
$serp_list_li[] = '<div class="serial-contain-' . $side . '">' // ...the rest

This would add a 'left' side first.

Comments

0

Get EvenArray and OddArray

NSArray *numberArray = [NSArray arrayWithObjects:@1,@2,@3,@4,@6,@8,@10, nil];
for (id object in numberArray)
    {
        if ([object integerValue] % 2 == 0) 
        {
            [evenArray addObject:object];
        } 
        else 
        {
            [oddArray addObject:object];
        }
    }

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.