user2284703
user2284703

Reputation: 367

$_POST array sometimes skips numbers and IF statement ends

I can not figure out how to print all $_POST array items (ending in successive numbers) if one or more numbers do not exist. Not sure how to explain this... For example..

$i = 1; 
while( isset($options['item_code'.$i]) )
{
echo $options['item_code'.$i];
$i++;
} 

This code works fine as long as the numbers continue to exist in order...

item_code, item_code1, item_code2, item_code3, etc...

But once a number is removed, the if statement stops and the rest of the values are not printed. For example...

item_code, item_code1, item_code3, etc...

Will stop at "item_code1" because item_code2 does not exist.

I've tried solutions given to similar questions here on stackoverflow but they either do not work, do the same thing, or create a continuous loop.

I would appreciate any help that someone can give me here.

Upvotes: 1

Views: 42

Answers (3)

Amit Sharma
Amit Sharma

Reputation: 1795

you are doing it in wrong way. Please update your code like this. replace $i<=4 with number of element you want to trace

$key =  end(array_keys($options));
$dataa = explode('item_code',$key);
$count = $dataa[1];


$i = 1;
while( $i <= $count )
{
   if(isset($options['item_code'.$i])){
      echo $options['item_code'.$i];
   }
   $i++;
} 

Upvotes: 1

Andrii  Filenko
Andrii Filenko

Reputation: 984

I guess it can be done with an array_filter and strpos functions:

<?php 

$codes = array_filter($options, function ($key) {
    return strpos($key, 'item_code') === 0;
}, ARRAY_FILTER_USE_KEY);

foreach ($codes as $code) {
    echo $code . PHP_EOL;
}

Upvotes: 1

vivek modi
vivek modi

Reputation: 812

Instead of while use foreach like

foreach($options as $option){
    echo $value;
}

Upvotes: 0

Related Questions