I have a PHP array as below :
Array
(
[0] => QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)
[1] => Microsoft Network Adapter Multiplexor Driver
[2] => QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client) #75
[3] => QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)
)
I need to identify duplicate values from PHP array and rename using number at the end as below,
Array
(
[0] => QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)_1
[1] => Microsoft Network Adapter Multiplexor Driver
[2] => QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client) #75
[3] => QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)_2
)
I tried array_count_values() to detect duplicates but how can i rename it ? https://onlinephp.io/c/739cb
CodePudding user response:
This should do the trick:
$originalArray = array(
"QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)",
"Microsoft Network Adapter Multiplexor Driver",
"Microsoft Network Adapter Multiplexor Driver Simplified",
"QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client) #75",
"QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)",
"Microsoft Network Adapter Multiplexor Driver",
"QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)",
"QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)",
);
$arrayCountVals = array_count_values($originalArray);
foreach ($arrayCountVals as $key => $count) {
$increment = 1;
if ($count === 1) continue;
foreach ($originalArray as $k => $entry) {
if ($entry === $key) {
$originalArray[$k] = $entry . "_" . ($increment);
$increment = 1;
}
}
}
This changes the original array so if you may want to create a copy and update the copy if you need to maintain the original. But since where you're array comes from wasn't included in your code, I'm not sure whether you need that or not.
CodePudding user response:
Create a lookup array of values which occur more than once. Then iterate the input array (modifying the values by reference), and conditionally increment the value's counter and append it to the string.
Code: (Demo)
$lookup = [];
foreach (array_count_values($array) as $value => $count) {
if ($count > 1) {
$lookup[$value] = 0;
}
}
foreach ($array as &$value) {
$value .= (isset($lookup[$value]) ? "_" . $lookup[$value] : '');
}
var_export($array);
Output:
array (
0 => 'QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)_1',
1 => 'Microsoft Network Adapter Multiplexor Driver_1',
2 => 'Microsoft Network Adapter Multiplexor Driver Simplified',
3 => 'QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client) #75',
4 => 'QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)_2',
5 => 'Microsoft Network Adapter Multiplexor Driver_2',
6 => 'QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)_3',
7 => 'QLogic BCM57810 10 Gigabit Ethernet (NDIS VBD Client)_4',
)
If you like compact code, the population of the lookup array can be done like this:
$lookup = array_map(fn() => 0, array_diff(array_count_values($array), [1]));