0

I have something like this => "1,2,3" that I get this from the user (that is just an example because I do not know those numbers)

I want to get those numbers and insert each number into an array like $numbers

$numbers['0'] = 1;
$numbers['1'] = 2;

how can I do that?

3 Answers3

3

You can use explode to split the string by comma and get a array:

$str = "1,2,3";
$numbers = explode(",",$str);
print_r($numbers);

Which will output,

Array ( [0] => 1 [1] => 2 [2] => 3 )

Which is,

$numbers[0] = 1;
$numbers[1] = 2;
$numbers[2] = 3;

You can copy paste the above code and try here phptester

sietse85
  • 1,488
  • 1
  • 10
  • 26
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
2

In this case explode function is your friend !

$numbers = explode(",", $input);
Ramy Herrira
  • 574
  • 10
  • 13
0

Try this. For example if you get user input from form which is stored in $_POST variable

foreach ($_POST as $key => $value) {
  $newArray[$key] = $value;
}

print_r($newArray);
Zain Farooq
  • 2,956
  • 3
  • 20
  • 42