reading a file

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I have a file which has a bunch of entries (student's data). Its structure
looks like


As can be seen, the entries are seperated by a "|".

Now I would like to create 5 arrays where I store all the entries
seperatly, for instance an array for the ID, one for the name ....

How do I read out the file and save the data to the arrays?



Re: reading a file

Quoted text here. Click to load it


Quoted text here. Click to load it

Take a look at the filesystem functions:

A simple (but surely not the most memory efficient way)

-file() to read the datafile in an array
-for(each) to loop through the entries
-explode to seperate the entries per line
-add those (for(each) loop) to your per type arrays

fopen/fgetcsv would be more efficient.


  Daniel Tryba

Re: reading a file

Christian Christmann wrote:
Quoted text here. Click to load it

This should work (UNTESTED):
$num = array();
$id = array();
$name = array();
$surname = array();
$email = array();

$arr = file('path/to/file');
$arrcount = count($arr);

foreach($arr as $val)
  list($num[], $id[], $name[], $surname[], $email[]) = split('|', $val);

This is a bit shorter but doesn't give you 5 seperate arrays (UNTESTED):

$newarray = array();

$arr = file('path/to/file');

foreach($arr as $val)
  $newarray[] = split('|', $arr);

I will leave the error checking up to you...


Shawn Wilson

Site Timeline