Innov Bee
Innov Bee

Reputation: 37

For each odd item in php array

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 }} ?>

Upvotes: 0

Views: 390

Answers (3)

DeepBlue
DeepBlue

Reputation: 694

Try this:

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

Upvotes: 0

Daniel Lagiň
Daniel Lagiň

Reputation: 728

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.

Upvotes: 0

Chin Leung
Chin Leung

Reputation: 14921

Use a for loop instead.

for($i=0; $i<count($items); $i+=2)
    echo $items[$i] . '<br>';

Upvotes: 2

Related Questions