Reputation: 687
I have an ini file like below
[PeopleA]
names=jack, tom, travis
color=red, blue, orange
[PeopleB]
names=sam, chris, kyle
color=purple, green, cyan
The goal is to pull a specific value and remove it using PHP
My code:
remove_ini($file, 'PeopleA', 'names', 'jack'); // call function
function remove_ini($file, $section, $key, $value) {
$config_data = parse_ini_file($file, true);
$raw_list = $config_data[$section][$key];
$list = explode(", ", $raw_list);
$index = array_search($value, $list);
unset($list[$index]); //remove from list
$config_data[$section][$key] = ''; // empty config_data
foreach($list as $list_item){ // re-iterate through and add to config_data w/o val passed in
if (empty($config_data[$section][$key])) {
$config_data[$section][$key] = $list_item;
} else {
$config_data[$section][$key] .= ', ' . $list_item;
}
}
$new_content = '';
foreach ($config_data as $section => $section_content) {
$section_content = array_map(function($value, $key) {
return "$key=$value";
}, array_values($section_content), array_keys($section_content));
$section_content = implode("\n", $section_content);
$new_content .= "[$section]\n$section_content\n";
}
file_put_contents($file, $new_content);
}
What seems to happen is it removes the first time this executes, but after that it starts to remove to remaining values.
I just call the function with remove_ini($file, 'PeopleA', 'names', 'jack');
.
Not sure whats going on or why it is removing more than items named 'jack', could use some insight. Thanks!
Upvotes: 1
Views: 325
Reputation: 1146
remove('file.ini', 'PeopleA', 'names', 'travis');
function remove($file, $section, $key, $value, $delimiter = ', ')
{
$ini = parse_ini_file($file, true);
if (!isset($ini[$section]) or !isset($ini[$section][$key]))
{
return false;
}
$values = explode($delimiter, $ini[$section][$key]);
$values = array_diff($values, [$value]);
$values = implode($delimiter, $values);
if ($values)
{
$ini[$section][$key] = $values;
}
else
{
unset($ini[$section][$key]);
}
$output = [];
foreach ($ini as $section => $values)
{
$output[] = "[$section]";
foreach ($values as $key => $val)
{
$output[] = "$key = $val";
}
}
$output = implode(PHP_EOL, $output);
return file_put_contents($file, $output);
}
Upvotes: 1