Get the first character of $key['Name']
and then compare it to the variable $name
. If there is a match, then add $key['Hours']
to a variable. Keep on doing that for each item in arrayChart.
$name = "M";
$hours = 0;
foreach($arrayChart as $key){
if ($key['Name'][0] === $name) {
$hours += $key["Hours"];
}
}
print_r($hours);
Example: https://rextester.com/VFPH10481
Also check out this question: Getting the first character of a string with $str[0]
EDIT
If $name = "Mike"
is a requirement, you could do this:
$name = 'M';
$hours = 0;
foreach($arrayChart as $key){
$foundAtPosition = strpos($key['Name'], $name);
if ($foundAtPosition === false ||
$foundAtPosition > 0) {
continue;
}
$hours += $key["Hours"];
}
print_r($hours);
Example: https://rextester.com/ZHCG76001
Explanation: Check out the manual for strpos function. Using that function, you can find the position where $name
is found in your $key['Name']
. If it is not found, strpos will result in false. If it is found, strpos will tell you where it is found.
strpos will show 0
if $name
occurs at the beginning. Using that logic, you can ask your loop to skip if result of strpos is false or greater than 0. Otherwise, you can calculate hours.
If you want case-insensitive search, use stripos function instead.
EDIT 2
If you want to extract IDs along with hours, you could do this:
$name = 'M';
$hours = 0;
$ids = array();
foreach($arrayChart as $key){
$foundAtPosition = strpos($key['Name'], $name);
if ($foundAtPosition === false ||
$foundAtPosition > 0) {
continue;
}
$hours += $key["Hours"];
$ids[] = $key['ID'];
}
echo $hours . "\n";
echo join(',', $ids) . "\n";
Example: https://rextester.com/ZRIC46050
Explanation: We create an empty array variable called $ids
. When we find our match, we add the ID of Mike or M (or whatever you are matching) into the array. $ids[] = 'something'
means, add something
at the end of $ids variable. To print that variable as a comma-separated value use the join
function, which joins each item of the array using a comma in the above code.