0

I have a textarea box that takes barcodes separated by a new line. When they are processed, the new lines become commas. But if somebody inputs:

123456


234567
...

with a bunch of spaces under each code as such, it then becomes

$barcode_list = 123456,,,234567

I am able to strip the commas from the end, and I have tried:

$array = explode(",", $barcode_list);
foreach($array as $item){ //Separate each item
    if ($item == "") {
        unset($item);
    }

but it doens't seem to work, I still get mysqli errors etc. Is there any way to get around this?

2 Answers2

0

You're doing an unset that doesn't really affect your array.

Do this:

$array = explode(",", $barcode_list);
foreach($array as $key => $item){ //Separate each item
    if ($item == "") {
        unset($array[$key]);
    }
}
dokgu
  • 4,957
  • 3
  • 39
  • 77
0

You should first remove unnecessary commas, then explode. Fewer steps...

// every sequence of commas becomes one comma 
$barcode_list=preg_replace("/,+/",",",$barcode_list);
// explode the string into an array
$array = explode(",", $barcode_list);
Ruby Racer
  • 5,690
  • 1
  • 26
  • 43