cannot write value into file via PHP
I have a configuration file like the following,
NameA=3
NameB=2
NameC=1
The following code tries to find NameC, and replace its value. Suppose here I pass in the value 0.
public function writeScreenSwitch($isTick)
{
$filename = 'my/file/path';
$data = parse_ini_file($filename);
$replace_with = array(
'NameC' => $isTick
);
// After print out $replace_with value, I'm sure the value is,
// [NameC] => 0
$fh = fopen($filename, 'w');
foreach ( $data as $key => $value )
{
if ( !empty($replace_with[$key]) ) {
$value = $replace_with[$key];
} else {
echo "array empty";
// the problem is here.
// $replace_with[$key] is always empty.
// but before the loop, the value $replace_with['NameC']=0
// why.
}
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
fclose($fh);
}
I have described the problem on the cod开发者_如何学Goe.
Because 0 is counted as EMPTY. That's why you are getting this.
Check here
The problem is with the empty() function, have a look at the remarks in the Return Values section. What you're needing to check for is if it is set, using the isset() function:
public function writeScreenSwitch($isTick)
{
$filename = 'my/file/path';
$data = parse_ini_file($filename);
$replace_with = array(
'NameC' => $isTick
);
// After print out $replace_with value, I'm sure the value is,
// [NameC] => 0
$fh = fopen($filename, 'w');
foreach ( $data as $key => $value )
{
if ( isset($replace_with[$key]) ) {
$value = $replace_with[$key];
} else {
echo "array not set";
// the problem is here.
// $replace_with[$key] is always empty.
// but before the loop, the value $replace_with['NameC']=0
// why.
}
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
fclose($fh);
}
That should do the trick. ;)
精彩评论