Search code examples
phpsplitfetchall

How to i split String by new line and by ";" and then fetchall as row


I have txt file which looks like

Stefan;Mihajlovic;2;3, 2, 3, 2, 3, 2;100
Milutin;Milankovic;1;2, 3, 4, 5, 6, 89;1000

I managed to split it by new line using code below

$array = file('test.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    var_dump($array);

Output is this:

array(2) { 
[0]=> string(82) "Stefan;Mihajlovic;2;3, 2, 3, 2, 3, 2;100" 
[1]=> string(82) "Milutin;Milankovic;1;2, 3, 4, 5, 6, 89;1000" 
}

What I need now is to split every array by ";" and fetch all as a row. Honestly, I started learning PHP a few days ago so I have no idea how to do it. Any help is appreciated

UPDATE Sorry i forgot to mention that i need to do it dynamically since new lines will be added every day.


Solution

  • You can use explode() function to create array from string by ;

    $newArray = array( 
      "Stefan;Mihajlovic;2;3, 2, 3, 2, 3, 2;100",
      "Milutin;Milankovic;1;2, 3, 4, 5, 6, 89;1000" 
    );
    foreach($newArray as $arr) {
       print_r(explode(";",$arr));
    }
    

    Output:

    Array
    (
        [0] => Stefan
        [1] => Mihajlovic
        [2] => 2
        [3] => 3, 2, 3, 2, 3, 2
        [4] => 100
    )
    
    Array
    (
        [0] => Milutin
        [1] => Milankovic
        [2] => 1
        [3] => 2, 3, 4, 5, 6, 89
        [4] => 1000
    )