1

I tried to run the following lines inside the run() function of a Laravel seeder.

$numbers = <<<EOL
1
2
3
4
EOL;

$array = explode(PHP_EOL, $numbers);

After run php artisan migrate:refresh --seed, I noticed that the $array value was:

Array (
  0 => '1
2
3
4',
)

The expected result was:

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

Why the explode() function within a seeder ignores the end of lines?

cespon
  • 5,630
  • 7
  • 33
  • 47
  • 1
    It depends entirely on how you generated the line breaks when you wrote the code. If your editor did not use the system `PHP_EOL` then `explode()` won't match them. – Don't Panic Mar 03 '19 at 21:58

2 Answers2

3

works fine

$numbers = <<<EOL
1
2
3
4
EOL;

$array = explode("\n", $numbers)

The purpose of PHP_EOL is to automatically choose the correct character for the platform. For DOS PHP_EOL - \r\n, mac - \r, unix - \n. In current situation u need to use statically \n.

Vlad Chornyi
  • 268
  • 2
  • 6
  • Did you test it in a seeder? – cespon Mar 03 '19 at 20:26
  • 1
    @cespon I have just tested this in a Seeder and it works as expected. I think there is something to do with the fact that `PHP_EOL === '\r\n'` whereas that string only has `\n` I will do some digging when I get some time. – JustCarty Mar 03 '19 at 21:16
0

If you are using Windows, the files that you create with Artisan (like seeders) have Unix line endings (\n) while the files created by your editor have DOS line endings probably (\r\n).

On Windows, the value of PHP_EOL is \r\n and the line endings of the seeders are \n, so the explode() function won't return a expected result.

Options:

  • You can use explode("\n", $numbers) (using double quotes, not single quotes).
  • Or, use explode(PHP_EOL, $numbers) and edit the line ending configuration of your editor for the specific file (Sublime Text example below).

enter image description here

cespon
  • 5,630
  • 7
  • 33
  • 47