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!

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

Daniel Peterson
Daniel Peterson
4,456 Points

Confused about key value order for array functions

Here is the correct code from the lesson: function print_info($value, $key){ echo "$key is a $value.</br>"; }

The thing that is confusing me is that it print_info uses the order of value then key, instead of key then value.

But I would expect that it should be key then value, like this: print_info($key, $value)

Is it the case that when working with array keys/values in other functions like example($x, $y), that $x is refers to the value and $y refers to the key?


2 Answers

You are confused because he was dealing with the PHP function array_walk(). Array_walk goes through a user supplied function and has a specific syntax. In the video, Hampton creates a user defined function (a requirement for array_walk). The function requires two input, the value from the array and the key. The array_walk function documentation states that the user defined function has two input: the value then the key in that order. Thus he structured his function in that order.

Take a minute to read the link in the previous paragraph. That will explain why it was structured that way in the video.

Daniel Peterson
Daniel Peterson
4,456 Points

Thanks for the answer.

Ok, so the input order for array_walk is defined and clear.

But he uses that same order for his user-defined function as well:

function print_info($value, $key){ echo "$key is a $value.</br>"; }

So I'm thinking that the php default for handing arrays is value then key. And maybe this makes sense because arrays always have a value, but don't always have non-default keys.

No, the default is not value, key. This is from the documentation for array_walk:


Typically, callback takes on two parameters. The array parameter's value being the first, and the >key/index second

He read the documentation for array_walk and created his callback function to comply with the array_walk documentation. A normal array looks like this:

array [ key1 => data1, key2 => data2, key3 => data3 ];

It is a little confusing and I missed this issue the first time I watched the video. Answering your question has helped clarify it for me.

It depends on the language and the function. For the most part, it's key and then value. As a programmer, you can create your own functions to implement what makes sense to you.