1

Say that I have an associative array of different types of fruits in baskets and the amount in each basket ('Banana'=>50 and etc) and I need to know how many of each type of fruit there is, but I don't know the possible types of fruit before I start the loop that generates the array. This may result in duplicate entries such as:

$baskets = array(
   "Apple"=>"35", 
   "Banana"=>"37", 
   "Apple"=>"43"
);

Question A: Is it even possible to make the second "Apple" entry or will it result in an error?

The answer was: Not possible, it would overwrite the first one with 43


Question B1: Assuming that the answer to A is "It's possible", how do I merge the two so that $baskets becomes ("Apple"=>"78","Banana"=>"37")?

Question B2: Assuming that the answer to A is "Not possible", how do I go about figuring out if there's already apples in the array and add the amount to the entry rather than attempting to add it as a new point in the array?

An answer to B2 will obviously make B1 obsolete even if A is "possible".

If neither B1 nor B2 are possible, then is there some other way that I can keep track of the amount of each type of fruit as I loop through the baskets?

Thanks for all of the helpful answers.

3
  • 1
    A: no, yes error, B2: array_key_exists(). Commented Aug 26, 2016 at 16:40
  • You can't have duplicate keys in an array. It will surely throw an error. But you can have an array inside an array so you can have multile values for the key. Commented Aug 26, 2016 at 16:40
  • if (isset($baskets[$currentFruit])) { // add to existing entry } else { // add new fruit entry}. Commented Aug 26, 2016 at 16:48

4 Answers 4

1

Q A: No Q B:

if(isset($baskets["apple"]))
{
  $baskets["apple"] = $baskets["apple"] + VALUE
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was a lot simpler than expected. Somehow I was stuck in the mindset of doing a second loop in which I would have to refer to the values and keys explicitly.
1

You will never get the duplicate keys in an array, there can only be unique keys. You will be only overwriting values for the key of duplicate fruits.

Answer B: due to the reason mentioned above, you will have to check in your loop whether the key exists in your resulting array, and if it does, add the new value to the existing one, otherwise store the value under this key.

Answer to B1: see answer to A.

Answer to B2: array_key_exists or isset

The algorithm depends on the way your data is stored. Maybe there's a more clever way possible.

Comments

1

Question A: Is it even possible to make the second "Apple" entry or will it result in an error?

No, would it be so hard to try it out?

 $basket['apple']=35;
 $basket['apple']=43;
 print $basket['apple']; // the output will be 43

The second assignment overwrites the former.

how do I merge the two

You could simply do this:

$basket['apple']+=35;
$basket['apple']+=43;
print $basket['apple'];

The problem with this is that the first time you reference an entry in the array, a PHP warning will be triggerred as it does not yet exist. While you should have your error reporting disabled (but error logging enabled) on your production system, this causes performance and support issues, hence a better solution is....

function add_to($basket, $product, $amount)
{
   if (isset($basket[$product])) {
      $basket[$product]+=$amount;
   } else {
      $basket[$product]=$amount;
   }
}
add_to($basket, 'apple', 35);
add_to($basket, 'apple', 43);
print $basket['apple']; // output will be 78

1 Comment

"The second assignment overwrites the former." Thanks for the clarity on that. I might find some use for your solution suggestion as well in case the way that I go about this code calls for it, so thanks for that.
-1

It is not possible to have the same key ('Apple') more then once in an associative array. If you are looping through and come across 'Apple' twice, the second entry will override the first:

array['Apple'] = 35
array['Banana']= 37
array['Apple' = 43

would result in an array:

( 'Apple' => 43, 'Banana' = 37 )

See Labradorcode's answer for the correct implementation and don't forget to cast your string values as ints!

EDIT to elaborate on his answer

for($i = 0; i < count(list_of_fruits){
    if(!array_key_exists($fruit, $basket){
        $basket[$fruit] = 0;
    }
    $basket[$fruit] = $basket[$fruit] + (int)$num_fruits;

something like that

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.