-2

I'm trying to convert these integers/numbers:

$groups = '1707,1723,1733,16254,16256,18704,19792,29268,34956';

into an array in PHP array:

array("1707","1723","1733","29268","34956");

I'm using this

 $tags = array();
 foreach($groups as $index){
     array_push($tags, $index);
  }

But keep getting the below error.

 Error: Invalid argument supplied for foreach()
lotsonj
  • 13
  • 1
  • 4
  • Use [explode](http://www.php.net/explode): `explode(",", $groups);` You probably have to [trim](http://www.php.net/trim) the individual results afterwards in case your input is something like `1707, 1723, 1733` etc. (spaces after commas) – ccKep Apr 02 '18 at 22:03
  • 2
    Do you want to remove `16254,16256,18704,19792`? – Syscall Apr 02 '18 at 22:03
  • Read about [`foreach`](http://php.net/manual/en/control-structures.foreach.php). It expects an array (or an object that implements `Iterable`) but you provide it a string. It doesn't work this way. [`explode()`](http://php.net/manual/en/function.explode.php) splits your string into pieces and produces an array. You don't even need to iterate over it as it produces the `$tags` you need. – axiac Apr 02 '18 at 22:08

2 Answers2

2

simple explode call:

$array=explode(',',$groups);
1

The explode() function breaks a string into an array.

$groups = '1707,1723,1733,16254,16256,18704,19792,29268,34956';
print_r(explode(",",$groups));
Dhiarj Sharma
  • 328
  • 3
  • 12