1

So, I'm trying to understand how can I do this. I'm having a hard time with it.

$arrayChart = array(
array(
    "Name" => "Mike",
    "ID" => "0001234",
    "Hours" => 38
    ),
array(
    "Name" => "Miles",
    "ID" => "0005678",
    "Hours" => 42
    )
);

I want to be able to find the hours (integer) from the key values. The thing is that I want to find it based on the first letter of the names. Which means that if I have "M", every name that start with "M" I should output their working hours for the week and add them together.

So, I'm given "M", I have to find from that their working hours and add them. How can I do that? I tried using this function but that doesn't even do anything.

$name = "M";
foreach($arrayChart as $key){
if($key["Name"] == $name){
    $hours = $key["Hours"];
    break;
 }
}
print_r($hours);
Joe
  • 83
  • 9
  • 3
    You need to compare against the first letter of the name. Also you need to *add* to `$hours` (`+=`), not assign (`=`) to it, and you shouldn't `break` when you find a match. Try something like https://3v4l.org/NEXYI – Nick Oct 24 '20 at 01:02
  • I understood the other tips you gave me and solutions. The only thing I don't understand is how to compare the first letter. I want to be able to find the values from the given letter. I'm still learning PHP and I don't think I can do that yet. – Joe Oct 24 '20 at 01:09
  • `$string[0]` gives you the first letter of `$string`, so the code that I linked to uses `$key["Name"][0]` to access the first letter of `$key["Name"]` – Nick Oct 24 '20 at 01:12
  • But that would be hard coded if I use [0]. I'm trying to learn in a way where I can do it without hard-coding. – Joe Oct 24 '20 at 01:15
  • Yes, but "first" has only one meaning, so hard-coding it is fine. If you wanted to compare different letters, you could try something like https://3v4l.org/oCjUY – Nick Oct 24 '20 at 01:16
  • In my case I don't want to hard code because this problem seems easy, yet tricky. I'm trying to learn methods of finding the values. – Joe Oct 24 '20 at 01:21
  • Well, I've given you a couple of options that solve your current question. I would suggest playing with them with your actual data, and then asking a new question if you still have issues. – Nick Oct 24 '20 at 01:25
  • I appreciate your solution, which does work, but I'm not looking for hard-coding to get the answer. I wanted to see if doing some loop would do that, which I have not idea how. – Joe Oct 24 '20 at 01:26
  • 2
    Just change your `if` statement to `if(preg_match("/^{$name}/i", $key["Name"]))` and that should do the trick! – Steven Oct 24 '20 at 01:27
  • Well, that works. – Joe Oct 24 '20 at 01:38

1 Answers1

2

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.

zedfoxus
  • 35,121
  • 5
  • 64
  • 63
  • What if it was a full name instead of the first letter. Like having Mike G and Mike L. I don't think that would work since it looks hard-coded. – Joe Oct 24 '20 at 01:16
  • @Joe you mean `$name` could be `Mike G`? – zedfoxus Oct 24 '20 at 01:17
  • Instead of "M", I'm given "Mike" and then get the values for hours from the first name instead of the first letter. This way the method above won't work. – Joe Oct 24 '20 at 01:19
  • You should add those kinds of requirements in your question. If you are given the name `$name = "Mike"` and if the array has 2 names - `Mike Anderson` and `Mike Johnson`, what would be the output you are seeking? – zedfoxus Oct 24 '20 at 01:22
  • Sorry for not mentioning that. I'm asking IFF $name = "Mike" then how would I do the above function? The result I'm seeking is to find the total hours that all Mike worked. In this case there could be more arrays with different names. Also, for some reason the function doesn't output anything. It's blank. – Joe Oct 24 '20 at 01:24
  • @Joe No worries. I added an edit that will work for both the cases - if `$name` is `M` or `Mike`. Give it a shot. – zedfoxus Oct 24 '20 at 01:33
  • One last question. I previously had $hours = " ". I didn't include it here, but for some reason it doesn't print anything. If $hours = 0 then it does print. I'm trying to use this same method for finding the ID from all Mikes. It's not printing anything. – Joe Oct 24 '20 at 01:50
  • @Joe If you are adding integers, ensure that your variable is initialized with numeric zero instead of an empty string. So, `$hours = 0` initialization is a better choice. Do you want to print ID from all Mikes as comma separated like this `0001234, 0001235, 0001236` etc. or do you want them printed line by line? – zedfoxus Oct 24 '20 at 01:57
  • Doesn't matter how. With comma is fine. I'm just trying to understand arrays in php. So far you have helped a lot. – Joe Oct 24 '20 at 02:08
  • I've added an example to print IDs as a comma separated string. – zedfoxus Oct 24 '20 at 02:16
  • Okay, it's not working. Nothing it's printing out. Also, I forgot to mention that I'm trying to find the id using last name. If there is Mike G, Mike L and John G. Then $name = "G". – Joe Oct 24 '20 at 02:35
  • 1
    @Joe open a new question on StackOverflow with details you need and someone can answer that. Add example input and example output in your question. If something doesn't work, show what you get for output. Use rextester or other site to put your code, save the code to generate a link (if using rextester.com) and share that in your question. You'll get some good answers with those kinds of details. – zedfoxus Oct 24 '20 at 02:46