3

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.

  • 3
    PHP has a useful built-in function called [fgetcsv()](http://www.php.net/manual/en/function.fgetcsv.php), which would allow you to set the separator argument as a semi-colon (`;`)... the PHP Docs page that I've linked shows you how to use it – Mark Baker Jun 17 '16 at 10:22
  • Why reinventing the wheel? – B001ᛦ Jun 17 '16 at 10:22

4 Answers4

4

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
)
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27
1

Use explode function.

$a = "Stefan;Mihajlovic;2;3, 2, 3, 2, 3, 2;100";
$b = explode(";",$a);
var_dump($b);
KARTHI SRV
  • 499
  • 4
  • 20
1

Is this something like that you want to do ?

$myArrayRow = $tab[0];
$explodeArray = explode(";", $arraySplit);

echo $explodeArray[0] // Stefan
echo $explodeArray[1] // Mihajlovic

Check this link : http://php.net/manual/fr/function.explode.php

Naugrim.
  • 150
  • 1
  • 12
0

If I got what you want to do. You might try the explode function: for example:

$myString = "Stefan;Mihajlovic;2;3, 2, 3, 2, 3, 2;100";
$myArray = explode(';', $myString);
print_r($myArray);

you can try the code in this playground: http://www.tehplayground.com/#j3sy2ItTZ

cpanato
  • 409
  • 5
  • 8