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? :-\

 

 

 

Link to comment
Share on other sites

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 :)

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.