user1338194
user1338194

Reputation: 267

php Put contents of a file into an array and then split each string of this array into a seperate array

this is probably a ridiculous question to ask but i am learning php so please help if you can.

I have a file called 'res_example.txt' and it looks like this:

>chr1:2198584545754_genome_1000+ 511 66 (+) nan full_model
>chr2:2198581212154_genome_1000+ 649 70 (+) nan full_model
>chr3:2115151215754_genome_1000+ 666 80 (+) nan full_model
>chr4:2198584545754_genome_1000+ 750 90 (+) nan full_model
>chr5:1218455145754_genome_1000+ 800 100 (+) nan full_model
>chr6:1231354645454_genome_1000+ 850 110 (+) nan full_model
>chr7:1231213211134_genome_1000+ 900 120 (+) nan full_model

I want to open this file. Put each line into an array $resArray, so each line is a separate string. so it will be like this:

$resArray= array(' >chr1:2198584545754_genome_1000+ 511 66 (+) nan full_model',  '>chr2:2198581212154_genome_1000+ 649 70 (+) nan full_model')

etc

Then with Each key from $resArray, I want to create another Array $ArrayResults exploding each string at each space in the string. This will ow me to work with each part of each string separately.

I hope this ,made sense. I probably didn't ask the question in the right way, so Apologies.

Thanks for any help.

Upvotes: 0

Views: 1360

Answers (3)

CodeCaster
CodeCaster

Reputation: 151594

I want to open this file. Put each line into an array

file()

with Each key from $resArray, I want to create another Array $ArrayResults exploding each string at each space in the string

explode()

So it'll become something like this:

$resArray = file('res_example.txt');
$resSplit = array();

foreach ($resArray as $res)
{
    $resSplit[] = explode(' ', $res);
}

Upvotes: 4

bunsiChi
bunsiChi

Reputation: 125

You might want to look at explode(), you can find it here. Cheers.

Upvotes: 1

Honoki
Honoki

Reputation: 461

First, get the contents of your file, and put them in the variable contents.

$f = fopen('filename.txt', 'r+');
$contents = fread($f, filesize("filename.txt"));
fclose($f);

Next, split the content on the newline character \n (or \r\n if you're on a Windows machine).

$resArray = explode("\n",$contents);

And finally, loop through the array to split each value on the space character.

foreach($resArray as $r) {
   $ArrayResults[] = explode(" ",$r);
}

I hope that's what you're looking for.

Upvotes: 1

Related Questions