0

I am trying to print every 2nd item or an array starting with 1 so the 1st, 3rd, 5th element etc. My current code give illegal offset type error

$array2 = array(explode(',', $prodorder));

<?php foreach($array2 as $value) { 
    if ($value % 205 !== 0) {

        $productscore =  $_POST[$value];
        echo $value;
?>

    <tr><td><?php echo $productname;?></td><td><?php    echo $productdescription;?></td></tr>

    <?php }} ?>

3 Answers 3

2

Use a for loop instead.

for($i=0; $i<count($items); $i+=2)
    echo $items[$i] . '<br>';
Sign up to request clarification or add additional context in comments.

1 Comment

I have changed to the above but this isn't echoing out anything. My array values are 1,2,4,9 and I am expecting 1 and 4 to be echoed
0

This will also work, but using for loop is better and more elegant way.

$array2 = [
  "value1",
  "value2",
  "value3",
  "value4",
  "value5"  
];  
//$array2 = array_values($array2);

foreach($array2 as $k => $v) { 
   if (($k + 1) % 2 == 1) {   
       echo $v;
   }  
} 

Also this cant be used in associative array, unless you use array_values.

Comments

0

Try this:

foreach($array2 as $k=>$value) { 
    if ($k % 2 !== 0) {
        $productscore =  $_POST[$value];
        echo $value;
    }
}

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.