file(), file_get_contents(), or something else?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
oboedrew
Forum Commoner
Posts: 78
Joined: Fri Feb 20, 2009 1:17 pm

file(), file_get_contents(), or something else?

Post by oboedrew »

Hello, everyone. I've got a PHP question. I'm trying to find a way to open a file and create an array from it, as if using file(). However, I'd like the first line to be file[0], the second to be file[1], and then starting on the third line I'd like to read the rest of the file as a string, as if using file_get_contents(), and make that entire string file[2], even though that string may take up a number of lines in the text file. Is this possible?

Thanks,
Drew
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: file(), file_get_contents(), or something else?

Post by pickle »

Do you want $file[2] to consist of the entire file, or just lines from the third line on?
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
oboedrew
Forum Commoner
Posts: 78
Joined: Fri Feb 20, 2009 1:17 pm

Re: file(), file_get_contents(), or something else?

Post by oboedrew »

$file[2] should contain everything from the third line on. So, basically, I'm trying to read the first two lines with file(), and then read the rest of the lines with file_get_contents().

Cheers,
Drew
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: file(), file_get_contents(), or something else?

Post by pickle »

  • Open the file with file()
  • array_shift() the first element off & store it in a new array
  • array_shift() the first element off again & store it in the new array (this would be the second line of the file)
  • call implode() on the original array, and store the result in the [2] element of the new array
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
oboedrew
Forum Commoner
Posts: 78
Joined: Fri Feb 20, 2009 1:17 pm

Re: file(), file_get_contents(), or something else?

Post by oboedrew »

Ooh, very clever, pickle. I'll try that out. I had never even heard of the array_shift() function.

Thanks,
Drew
Post Reply