Skip to content
Advertisement

else, elseif,else statement is not working with fwrite in php

i want to write expiry date in a text file with respect to condition but when i echo in browser, it works fine but at the same time it is not writing in text file. Here is my code:

condition is based on user selection, problem is that instead of writing expiry date in expiry.cfg, it write only condition like 1,2 or 3. please guide how to resolve this issue.

$expiry1 = date('Y-m-d H:i:s', strtotime('1 Month'));
$expiry2 = date('Y-m-d H:i:s', strtotime('3 Month'));
$expiry3 = date('Y-m-d H:i:s', strtotime('6 Month'));

$condition = 1;

if ($condition == "1") {
    echo $expiry1;
} elseif($condition == "2") {
    echo $expiry2;
} else{
    echo $expiry3;
}
$myfile = fopen("/var/etc/expiry.cfg", "a") or die("Unable to open file!");
fwrite($myfile,$condition);
fclose($myfile);```

Advertisement

Answer

Try this,

<?php
$expiry = [];
$expiry[1] = date('Y-m-d H:i:s', strtotime('1 Month'));
$expiry[2] = date('Y-m-d H:i:s', strtotime('3 Month'));
$expiry[3] = date('Y-m-d H:i:s', strtotime('6 Month'));

$condition = 1;

if (isset($expiry[$condition])) {
    $myfile = fopen("/var/etc/expiry.cfg", "a") or die("Unable to open file!");
    fwrite($myfile, $expiry[$condition]);
    fclose($myfile);
} else {
    echo 'Invalid condition';
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement