0

I have a textarea in my form where user will enter data line by line. I am processing it using $_POST . I have to separate each line by a comma while echoing it in php

the text area content like this

233
123
abf
4c2

I tried with below code

$array = array($_POST['devices']);
$device = implode(",", $array);

echo $device;

But it not showing commas between each value, rather I will get plain values like

233 123 abf 4c2

How can I show it like

233,123,abf,4c2

All above values are part of the text area,

hakre
  • 193,403
  • 52
  • 435
  • 836
acr
  • 1,674
  • 11
  • 45
  • 77

2 Answers2

1

You can not split a string into an array simply by creating an array().

You need to convert it to an array by splitting the lines:

$devices = preg_split('/\s+/', $_POST['devices']);
echo implode(',', $devices');

Note: You may want to split strictly on line endings. But the above will get you started.

Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
1

No need to summon the power of regular expressions. You can simply implode the results of an explode.

$str = implode(",", explode("\n", $_POST['devices']));
Orangepill
  • 24,500
  • 3
  • 42
  • 63