Forum Moderators: coopster

Message Too Old, No Replies

Exploding an Array

         

Jeremy_H

5:50 pm on Nov 5, 2006 (gmt 0)

10+ Year Member



I have a file with multiple lines, each line contains information broken into three parts that is separated with commas:

FILE:

l0p0,l0p1,l0p2
l1p0,l1p1,l1p2
l2p0,l2p1,l2p2...

I want to use this information in a script, so I call the file using the following command:

$file=file("myfile.txt");

This breaks up the file into an array, with each key representing a different line.

I want to further break down this array efficiently as possible so that each line is exploded by the comma.

I'm wanting to get an output like this:

Array
(
[0] => Array
(
[0] => l0p0
[1] => l0p1
[2] => l0p2
)
[1] => Array
(
[0] => l1p0
[1] => l1p1
[2] => l1p2
)
[2] => Array
(
[0] => l2p0
[1] => l2p1
[2] => l2p2
)
)

I tried using this line: $file=explode(","file("myfile.txt")); but what it seems to be doing is just exploding the word "Array"

print_r $file[0][0] => "A"
print_r $file[0][1] => "r"

However, explode(",",$file[0]) seems to work.

How can I explode my array without having to do an explode command each time I want to use a value?

Thanks

eelixduppy

6:05 pm on Nov 5, 2006 (gmt 0)



Something like this should work:

$values = array();
foreach(file("myfile.txt") as $line => $content) {
$values[$line] = explode(',',$content);
}
echo '<pre>';
print_r($values);
echo '</pre>';

Good luck! :)

Jeremy_H

6:57 pm on Nov 5, 2006 (gmt 0)

10+ Year Member



Thank you very much for the reply, it works great.

I'll have to do some research on "foreach" and "as" since I'm not very familiar with what they do and why this function is working this way.

Thanks.

eelixduppy

7:23 pm on Nov 5, 2006 (gmt 0)



You're welcome.

Research done for you: [us3.php.net...]

;)

Jeremy_H

6:47 pm on Nov 6, 2006 (gmt 0)

10+ Year Member



Thanks,

That looks like a valuable tool!