-2

How can I convert loop result of string to an array? For instance, I have this strings:

$nmbrs = '111, 222, 333, 444';

This $nmbrs variable should come from an for loop as that:

$numberPrefixes = '__';
 
for ($i = 0; $i < 10; ++$i) {
     $numbers = $numberPrefixes . randomNumberSequencePhone(); 
}

$array1 = explode(',', $numbers);

var_dump($array1);

And I want to get:

array(4) {
  [0]=>
  string(1) "111"
  [1]=>
  string(1) "222"
  [2]=>
  string(1) "333"
  [3]=>
  string(1) "444"
}
Mohcin Bounouara
  • 593
  • 4
  • 18

2 Answers2

1
<?php
$nmbrs = '111, 222, 333, 444';

$array1 = explode(',', $nmbrs);


var_dump($array1);
?>
KUMAR
  • 1,993
  • 2
  • 9
  • 26
  • 1
    This will get extra space for 222, 333 and 444. – Syscall Feb 26 '21 at 10:19
  • When i do that outside the loop its give me just the first value of the array... $numberPrefixes = '__'; for ($i = 0; $i < 10; ++$i) { $numbers = $numberPrefixes . randomNumberSequencePhone(); } $array1 = explode(',', $numbers); var_dump($array1); – Mohcin Bounouara Feb 26 '21 at 10:33
1

explode(', ', $nmbrs)

You need the space after the comma so you don't get space character (" ") in your 2nd, 3rd and 4th array items.

increda_jaw
  • 86
  • 1
  • 10