Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);```
like image 645
Hammad Nazir Avatar asked Jun 14 '26 20:06

Hammad Nazir


1 Answers

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';
}
like image 51
Lawrence Cherone Avatar answered Jun 17 '26 08:06

Lawrence Cherone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!