Jump to content

[SOLVED] How to get entire file data into a single array ???


phpRoshan

Recommended Posts

yes. sory abt that.

 

what i ment was how to put the contents/words of the file in to array elements?

like

 

arr[0] = 'some word'

arr[1] = 'some othe word'

arr[2] = 'maybe a digit or digits?'

 

in this way.

 

i dont thing if i use  "$array = file('path/to/file');" it wont do that? does is? :-\

 

 

 

file() gives you an array containing each line in its own key. You can then split file() up, eg:

 

<?php

$filename = "path/to/file";

$lines = file($filename);

foreach($lines as $linenumber => $linedata) {
$words[$linenumber] = explode(" ", $linedata);
}

?>

 

Now you have an array ($words) with sub arrays containing the words in each line of the file found in $filename.

 

Not tested, but you get the idea :)

Try this way..

 

$filename = "path/to/file";

$data = file($filename);

function fileToArray($data) {
$words = explode(' ',$data);
foreach ($words as $word) {
	$outputArray[]=$word;
}
print_r($outputArray);
}
fileToArray($data);

 

Not tested yet but seems to be working in my mind.. lol

A little change on the above code

$filename = "path/to/file";
$data = file($filename);
function fileToArray($data) {
$words = preg_split('/\s+/',$data);
foreach ($words as $word) {
	$outputArray[]=$word;
}
print_r($outputArray);
}
fileToArray($data);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.