Print out specific values in array

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

herbertioz
New php-forum User
New php-forum User
Posts: 1
Joined: Thu Aug 07, 2014 2:47 am

Print out specific values in array

Postby herbertioz » Thu Aug 07, 2014 2:56 am

I have this code:

Code: Select all

<?php
$openFile = fopen("SP.csv", "r");
$fileContents = fread($openFile, filesize("SP.csv"));
fclose($openFile);
$delimiter = ",";
$myArray = explode($delimiter, $fileContents);
//echo $myArray['10'][0];
print_r($myArray[4]);
?>

Csv:
19820421, 116.350, 117.600, 116.050, 117.450, 7926, 1032
19820422, 117.000, 118.400, 117.000, 117.900, 5966, 1746
19820423, 118.350, 119.750, 118.250, 119.650, 6128, 2268

I am trying to print out all the values in an array in the position [4] for example:
117.450 117.900 and 119.650. How can I do it?

landi
php-forum Active User
php-forum Active User
Posts: 307
Joined: Thu Mar 15, 2012 3:59 pm

Re: Print out specific values in array

Postby landi » Thu Aug 07, 2014 3:26 am

Hi,
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

<?php
$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
-A


Return to “PHP coding => General”

Who is online

Users browsing this forum: No registered users and 3 guests