I have the following code but I'm trying to shorten it about one or two lines, as I believe the if
is unnecessary. Is there any way the code below can shortened to a singular line?
if(file_exists($myFile))
{
$fh = fopen($myFile, 'a');
fwrite($fh, $message."\n");
}
else
{
$fh = fopen($myFile, 'w');
fwrite($fh, $message."\n");
}
Umm... why? a
already does what you need out of the box.
Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
if (file_exists($myFile)) {
$fh = fopen($myFile, 'a');
fwrite($fh, $message."\n");
} else {
$fh = fopen($myFile, 'w');
fwrite($fh, $message."\n");
}
fclose($fh);
==
if (file_exists($myFile)) {
$fh = fopen($myFile, 'a');
} else {
$fh = fopen($myFile, 'w');
}
fwrite($fh, $message."\n");
fclose($fh);
==
$fh = fopen($myFile, (file_exists($myFile)) ? 'a' : 'w');
fwrite($fh, $message."\n");
fclose($fh);
== (because a
checks if the file exists and creates it if not)
$fh = fopen($myFile, 'a');
fwrite($fh, $message."\n");
fclose($fh);
==
file_put_contents($myFile, $message."\n", FILE_APPEND);
...of course, file_put_contents()
is only better if it is the only write you perform on a given handle. If you have any later calls to fwrite()
on the same file handle, you're better going with @Pekka's answer.
$method = (file_exists($myFile)) ? 'a' : 'w';
$fh = fopen($myFile,$method);
fwrite($fh, $message."\n");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With