I have a little problem of understanding with one of the exercise of my PHP learning book (Wrox, beginning with PHP 5.3).
This code is the part when we check is the files "count" exists. If it does not, we need to create it. Really not a high level of complexity, but I do have a problem with it. Here is how I would write it:
- Check if the files exists with !files_exist()
- If not, create it and initialise it to 0 with fopen() and fwrite()
- When it is not possible to create it, then (else) display a error message
Here is how they wrote it and I saw this structure a couple of time. When something is to be executed it comes in the "else" expression, at the end. In my logic, I would place to code to be executed in the "if" expression.
$counterFile = “./count.dat”;
if ( !file_exists( $counterFile ) ) {
if ( !( $handle = fopen( $counterFile, “w” ) ) ) {
die( “Cannot create the counter file.” );
} else {
fwrite( $handle, 0 );
fclose( $handle );
}
}
My questions:
1) Are there rules how to structure loop and why is a method better?
2) Is the code, inside the expression, executed or just checked if true?
$counterFile = “./count.dat”;
if ( !file_exists( $counterFile ) ) {
if ( !( $handle = fopen( $counterFile, “w” ) ) ) {
die( “Cannot create the counter file.” );
} else {
fopen( $counterFile, “w” ) // I thought this code is not executed in the if expression? This is why I would declare it right here.
fwrite( $handle, 0 );
fclose( $handle );
}
}
Thank you for your help. have a nice week.