Print out specific values in array

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
php-forum Active User
php-forum Active User
Posts: 388
Joined: Thu Mar 15, 2012 3:59 pm

Thu Aug 07, 2014 3:26 am

1) There are probably better functions than fread() to read a CSV file. Checkout: fgetcsv() (which I've not used) or file() which reads the entire file into an array, one line per array element.

2) If you want to parse the CSV yourself, then be aware that explode() will not work properly if any string contains a comma. i.e. this line will return 3 elements: (some spaces added for clarity)

Code: Select all

explode(',' , ' "a","Hello World","c" ');
But this line will (wrongly) return 4 elements because of the comma embdedded in the Hello,World string:

Code: Select all

explode(',' , ' "a","Hello,World","c" ');
If it wasn't for the embedded comma problem (and your data may not have this problem), then you could do this:

Code: Select all

$aFileContents = file("SP.csv"); // Read file into an array, one element per line
foreach ($aFileContents as $sLine) { // Get elements (lines), one at a time, into $sLine
  $delimiter = ",";
  $myArray = explode($delimiter, $sLine);
  echo $myArray[4]; // Print out the 5th element (go Milla!)
Hope that helps

Post Reply