I have a PHP array with strings as follows:
Tim Jones
Karl Smith
Tim Jones
T Jones
K Smith
Tim JONES
I want to obtain the count of the number of occurrences of each of the string in the array. I used array_count_values
. But it returns
Tim Jones : 2
Karl Smith : 1
T Jones : 1
K Smith : 1
Tim JONES : 1
But I need to check only the last names and the first letter of the first name also for counting
Tim Jones : 4
Karl Smith : 2
Any suggestions as to how to do this. Thanks
Edit
This is a more correct example. If the array is
Tim Jones
Karl Smith
Harry Jones
Tim Jones
T Jones
K Smith
Tim JONES
The output should be
Tim Jones : 4
Karl Smith : 2
Harry Jones : 1
I am not so familiar with PHP. I came across array_count_values
and tried it. But I need to do some array splitting and searching and counting.
Based on Chris code, this is what I have now
<?php
$names = array (
'Tim Jones',
'Karl Smith',
'Tim Jones',
'T Jones',
'K Smith',
'Tim JONES'
);
$counts = array();
$actualMap = array();
foreach ($names as $name) {
$last_name = strtolower(array_pop((explode(' ', $name))));
$first_name_letter = substr(strtolower(array_shift((explode(' ', $name)))), 0, 1);
$first_name = array_shift(explode(' ',$name));
$actualKey = $first_name . ' '. ucfirst($last_name);
$key = $first_name_letter . ' '. $last_name;
if (array_key_exists($key, $counts) === false){
$counts[$key] = 0;
$actualMap[$key] = $actualKey;
}
$counts[$key]++;
}
print_r($counts);
print_r($actualMap);
?>
I obtain the following
Array ( [t jones] => 4 [k smith] => 2 ) Array ( [t jones] => Tim Jones [k smith] => Karl Smith )
I need to replace the keys now
1) Run through the list creating a [(First letter + " " +unique last name, count=0) , ...]
list as you go.
Or
You can use array_unique. Here is the documentation
2) Then run through the list again comparing to the first list and add to a count for that unique last name.
Not 100% sure if this is what you are asking for but I would normalize the names in the array and then you can count them
$array=array("Tim Jones","Karl Smith","Tim Jones","T Jones","K Smith","Tim JONES");
function editArray($array){
foreach($array as $x){
list($firstname,$notfirst)=explode(" ",$x);
$newnames[]=strtolower($firstname[0]." ".$notfirst);
}
return $newnames;
}
$newarray=editArray($array);
print_r(array_count_values($newarray));