[Solved] PHP add counter to name if already exists in array


$arrayOfNames = array(
    array('clientName' => 'John'),
    array('clientName' => 'John'),
    array('clientName' => 'Mary'),
    array('clientName' => 'Mary'),
    array('clientName' => 'Mary'),
    array('clientName' => 'Tony'),
    array('clientName' => 'Alex')
);

$namesCount = array();

$finalNames = array_map(function ($item) use (&$namesCount) {
    if (!isset($namesCount[$item['clientName']])) {
        $namesCount[$item['clientName']] = 0;
    }

    $namesCount[$item['clientName']]++;

    $item['clientName'] = $item['clientName'] . ' ' . $namesCount[$item['clientName']];

    return $item;
}, $arrayOfNames);

array_map(function($item, $key) use ($namesCount, &$finalNames) {
    $finalNames[$key]['clientName'] = $namesCount[$item['clientName']] == 1
        ? str_replace(' 1', '', $finalNames[$key]['clientName'])
        : $finalNames[$key]['clientName'];
}, $arrayOfNames, array_keys($arrayOfNames));

echo '<pre>';
    var_dump($finalNames);
echo '</pre>';

The output would be:

array(7) {
  [0]=>
  array(1) {
    ["clientName"]=>
    string(6) "John 1"
  }
  [1]=>
  array(1) {
    ["clientName"]=>
    string(6) "John 2"
  }
  [2]=>
  array(1) {
    ["clientName"]=>
    string(6) "Mary 1"
  }
  [3]=>
  array(1) {
    ["clientName"]=>
    string(6) "Mary 2"
  }
  [4]=>
  array(1) {
    ["clientName"]=>
    string(6) "Mary 3"
  }
  [5]=>
  array(1) {
    ["clientName"]=>
    string(4) "Tony"
  }
  [6]=>
  array(1) {
    ["clientName"]=>
    string(4) "Alex"
  }
}

5

solved PHP add counter to name if already exists in array