else、elseif、else 语句在 php 中不适用于 fwrite

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

我想根据条件在文本文件中写入到期日期,但是当我在浏览器中回显时,它工作正常但同时它没有写入文本文件。这是我的代码:

条件是基于用户选择的,问题是在expiry.cfg中没有写过期日期,而是只写条件如1,2或3。请指导如何解决这个问题。

$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);```

试试这个,

<?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';
}