Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Functions PHP Internal Functions PHP Array Functions

yalın küçük
yalın küçük
4,810 Points

array_combine method has a problem with doubled values. Then PHP as a language has a problem.

There are 2 arrays. As in the video $names has 3 values and 2 of them have the same string; 'Teacher'.

$names = array( 'Mike' => 'Frog', 'Chris' => 'Teacher', 'Hampton' => 'Teacher', ); $kind = array( 'Subject1' => 'Human', 'Subject2' => 'Animal', 'Subject3' => 'Insect', ); print_r (array_combine($names, $kind));

The result is: Array ( [Frog] => Human [Teacher] => Insect )

----------However, the result below is what it is supposed to be. What is the reason for the result above?...

<?php $a = array('green', 'red', 'yellow'); $b = array('avocado', 'apple', 'banana'); $c = array_combine($a, $b);

print_r($c); ?>

Array ( [green] => avocado [red] => apple [yellow] => banana )

5 Answers

Shayne Laufenberg
Shayne Laufenberg
4,213 Points

The PHP array_combine function combines the keys inside each of the arrays together because you have two values with the same exact key the 3rd value is overwriting the second element causing it to only display the two elements when the arrays are combined. Not sure what you're using this for but this is an example of what you need to do to show all results. Hope this helped :)

$names = array( 'Mike' => 'Frog', 'Chris' => 'Teacher', 'Hampton' => 'Something Else'); 
$kind = array( 'Subject1' => 'Human', 'Subject2' => 'Animal', 'Subject3' => 'Insect'); 
print_r (array_combine($names, $kind));
yalın küçük
yalın küçük
4,810 Points

When you change it to something else I get that there is not any problem but overwriting is just stupid in my humble opinion. It is not logical. I say how dare you ( to PHP). This is not its business you know. This should not be up to PHP. Creators of PHP language should change it.

In this case, I may have the same values for different keys that I want to match up with different values in another array. I do not know why I will use it because I do not have any knowledge of the database system and I am a beginner. In time I may have the wisdom. I hope so... Thank you for the respond.

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

yalın küçük But that's sort of the point here. The keys should be unique strings. If I had $names = array('Jennifer' => 'Student', 'Jennifer' => 'Nordell', 'Jennifer' => 'Something something'); then what would you expect to get back from $names['Jennifer'];?

<?php

$names = array('Jennifer' => 'Student', 'Jennifer' => 'Nordell', 'Jennifer' => 'Something something');
echo $names['Jennifer'];

?>

I suggest you run this in workspaces to see what happens. You'll see that it will return the last result. To be clear, this is how PHP handles duplicate keys. Some language (such as Swift) don't allow them at all. In Swift your code will not compile if you attempt this.

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! If you'll scroll down a bit in this documentation under the user-contributed notes, you'll see that this is addressed. In the case where two keys are duplicated the second one takes precedence. In the example you showed, the value "Teacher" is going to become the key so it's the second one that will be mapped to the value in the second array, which leaves you with a key of Teacher and a value of "insect".

Hope that helps! :sparkles:

yalın küçük
yalın küçük
4,810 Points

Jeniffer it is not the result I am after but the logic. "What" is something you can find by working but why is important here. Thank you for the explanation. This array function does not work well I guess. That's all. I do not have to change the values. It is my concern not this functions'. It should combine but It does not. Creators should change it or I should change my perspective. :)The latter is easier I guess.

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

I think that might be wise. Many languages do not allow duplicate keys at all. Your code will not compile or run with it like that. PHP allows for it and keeps your code running, but it will return the last value of that key it encounters.

Michael Hulet
Michael Hulet
47,912 Points

Keys with different values are not only impossible to implement, but they also defeat their own purpose. A key is unique by definition. It is a reference to exactly one object, so you get the same object back every time you ask for it. It's like this for good reason. If one key could point to more than one object at a time, how would the language know which one to give back when you use that key? It's just like a normal variable. It can only store one thing at a time, including things that can hold more than one thing themselves. If a variable could hold more than one object, or a key could reference more than one object, the whole language would be lost in chaos. If you want to see what that's like, I suggest you try out Malbolge, as it's the only language I can think of that lets you do what you're suggesting (and trust me, there's a reason that language is named after Dante's 8th circle of Hell). If you want to reference more than one object with the same key, you should store it as an array instead.

Unique keys aren't just an arbitrary restriction imposed by PHP (and nearly every other language in existence), but they're a necessity of the implementation. When you define a key, it doesn't store the key's object in memory. Doing so would take up potentially a lot of extra RAM, and it could make key lookup really slow, depending how large the object you're using as a key is. To mitigate this, PHP (and almost every other language out there) hangs on to what's called a hash of the key, which is a big number that's generated based on the object you use as a key and its values. This number is almost certain to be unique for all original values. However, when you give the hash function the same input, it'll generate the same value every time. This way, you can use any key you want, but storing it will never take up more than a single register of memory instead of potentially thousands or more, which takes up a lot less space and makes using keys a whole lot faster. When you first set a key, it goes through the hash function, and the hash is stored and set to map to the value you give it. When you ask for a value from that array again, the key you give it goes through the hash function, and the resulting hash is compared to the hashes it already has stored, and if it finds an object for that hash, it gives back that object.

Given that context, the functionality of array_combine makes sense. The logical implementation of this function is just a simple loop, so it only looks at one key and value at a time. Any other implementation would carry unnecessary complexity and time implications that you'd have to worry about as the user of this function. In your example, it has 2 objects that produce the same hash that are both supposed to be used as keys. Keys must be unique, and these objects produce the same hash, so they must be treated as the same key. The function's internal loop looks at the first value and assigns it to the key, but when it moves onto the next key/value pair, the key is the same, so it sets that value to be the value for that key. However, let's consider if it had more complex analysis methods to try to resolve conflicts like this. If it encounters 2 string values, should it combine them into one string? Which one comes first? What if they're the same string? Does it still combine them, or does the value stay the same? Let's consider if it encounters 2 number values. How are those to be combined? Are they to be added, subtracted, multiplied, divided, or some other mathematical function? Should a value be appended to the other, so passing in 1 and 2 would produce 12? If so, what value comes first? What happens if it gets multiple values of the same number? Do they get combined, or does the original value persist? What happens if the function encounters values of 2 entirely disparate types that can't be combined? Arguably, when the function encounters a value for a key that's already set, it could put both values in another array and set the key to refer to that array, but that has lots of implications for you code that you may not realize, as then you'll have to implement some method for detecting an array choosing what value from it you want when you use that key.

You're right that the values of your data is not the language's business, and so the language takes that approach. Instead of it worrying about how to deal with value conflicts, it places that onus on you, the programmer. This is the most logical approach to the problem, as taking any other creates an insane amount of complexity that is impossible to resolve, as the language/computer can't just guess what you mean for it to do in the face of all these questions that need to be answered

yalın küçük
yalın küçük
4,810 Points

This is my first language course. First coding experience. In time I will have a deeper understanding of these concepts. Thanks.

yalın küçük
yalın küçük
4,810 Points

Michael Hulet,

That was really enlightening. Thank you so much for this extensive explanation. For the hash function I guess it is how the coding is interpreted by the computer. For this I am watching this video.

https://www.youtube.com/watch?v=MfhjkfocRR0

Inside the guy is telling that 4:34 for the Key: Paul and value: phone# the index in the hash table is 3. However, when there is a collision ( it says the index of another hash will be the same) something is created called "chain". In this case, key can be the same and different index can be created. Isn't that so.

Sorry for my ignorance. Trying to understand. It is the first time I have read hash function. I do not know what it is just googled it. Do you suggest videos for this subject? You may not and suggest me go on training by not focusing these things. That's I can understand. However, hash tables are interesting. Like that. Curiosity is a good thing but I do not want to digress.

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

I know that you asked Michael, but I'd like to give my opinion here if I may. Do not get bogged down right now with the hash. I know that there's at least one course here on Treehouse that goes into it a little bit (C#), but this is such a low-level implementation that you're likely to not ever really need to understand exactly what's going on under the hood until you are well into programming. The lesson I would take from all this is that keys are supposed to be unique and there's a good reason for that. This is true not only of PHP, but as Michael points out, almost all programming languages. While I admire your curiosity, in the spirit of helping you advance, I'd advise moving on :smiley:

Michael Hulet
Michael Hulet
47,912 Points

That looks like a great video, but chaining isn't there to enable you to use a single key to point to 2 values, but it's how the language handles if 2 different keys happen to have the same hash. It doesn't happen too often, but sometimes even the most robust hash functions output the same hash for 2 different keys (as is bound to happen sometimes when you're doing any kind of compression). For example, using the function that PHP uses to generate hashes for associative array keys, the strings "foo" and "oof" will have the same hash when the array contains 64 or fewer elements. These are entirely different strings, and thus, they should point to 2 entirely different values in an associative array, but they'll both point to the same index in the hash table. To mitigate this, PHP stores a chain (academia's computer science term for it is a "linked list", but you can think of it just as a fancy term for array right now) of the values at that index. Since even associative arrays in PHP technically have an order, it knows what index in that linked list to grab when you give it a key whose hash collides with another key. This is all just an implementation detail of associative arrays that PHP deals with for you, though, so you don't have to worry about it at all.

Hashes and hash functions and hash tables are all really a computer science topic, and I don't think Treehouse covers it very much. However, you'll hear a lot about the basics of them (even here) when it comes to password storage, as hashes are key to storing passwords securely in your server's database. That being said, you seem to be really interested in CS, and that's awesome! It's honestly pretty refreshing to bump into someone like that, as they're not too common around here tbh. My favorite CS course on the internet has gotta be Harvard's CS50. Don't let the Harvard name scare you, because it's actually pretty easy to follow. I took it when I was in 8th grade and understood everything just fine. Once you're comfortable with PHP, you should totally give it a look

S Ananda
S Ananda
9,474 Points

Michael and Jennifer. Thanks for your lengthy answers. I feel like I truly understand the function of keys now. Before it was a bit muddy. However, I realized that if all the keys in the world were the same, it would be a big mess, because everyone could get into everyone else's house, car, business, etc. So, needing a unique key makes perfect sense. Lightbulb moment for me, thanks.

Michael Hulet
Michael Hulet
47,912 Points

You just gave me a lightbulb moment about how to explain this topic. That's a great analogy!