0

Could someone help suggest in below php explode function, we are displaying script after 5th listing. How is it possible to display script exactly after 5th listing and 10th listing on a page which has more than 10 listings

We tried using

if ($i == 5 & $i== 10)

but it does not work

Below is original code - which displays script after 5th listing

   <?php
  $listings = explode("<hr/>", $list);
  $numberOfListings = count($listings);
  for($i = 0; $i < $numberOfListings; ++$i) 
    {
    if ($i == 5) 
    { ?> 

   <script>  </script>

    <?php }
    echo $listings[$i] . "<hr/>";
    }
    ?> 

Edit How is it like - if have to display a separate script on $i==9, could you advise.

1
  • if ($i == 4 || $i== 9) <== use this or start your itetration with $i=1 Commented Nov 11, 2013 at 5:15

3 Answers 3

2

Because $i starts at 0 (0 to 9 is 10, whilst 0 to 10 is 11). Try if ($i == 4 || $i== 9), with an or operator.

Also I would not use the && (the and operator), because it is unlikely $i will ever equal both 4 and 9. I'd suggest you read into Truth Tables (and maybe Propositional Calculus) because from seeing what you had tried originally, it would be helpful to understand how a truth table works.

Truth Table
(source: wlc.edu)

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

2 Comments

thnx it works and thnx for reference url too. i will go through it
Hello, Just a small help.. How is it like - if have to display a separate script on $i=9, could you advise. Am sorryo to not have asked that in first instance. Many thanks
0

You can use the contine, continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

                $arr = range(0,9);
                foreach($arr as $number) {
                    if($number < 5) {
                        continue;
                    }
                    print $number;
                }

Ref: http://php.net/manual/en/control-structures.continue.php

Comments

0

Try using modulus operator

$listings = explode("<hr/>", $list);
$numberOfListings = count($listings);


for($i = 1; $i < $numberOfListings; ++$i)
    {
    if ($i%5 == 0)
    {
        echo "in";
        ?>
        <script>  </script>
    <?php
    }
    echo $listings[$i-1] . "<hr/>";
}

Here we are looping from 1 and there for $i <= $numberOfListings and while listing we will use $listings[$i-1]

DEMO CODE AT http://codepad.viper-7.com/lrTOgP

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.