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 Function Returns and More Returning Values

Why do we need an array to return multiple values & why can't we use multiple variables to achieve the same results?

-

3 Answers

In PHP, functions can only return a single value. Due to something called function scope, variables created inside of a function are not accessible outside of it.

You could get around this by using global variables, but that is usually a poor design decision and will make your code difficult to manage and troubleshoot.

If your function is more complex and you need to return multiple different kinds of values, you may want to look into using classes or Exception handling.

Antonio De Rose
Antonio De Rose
20,884 Points

The answer to your question, I'd say more it is like the way, the programming has been meant to be done, in ways, as per to the requirement, for instance, if you want a variable to be passed, then it could be returned with a variable, but, if there are multiple values to be sent, then array is the option, it would come to any programmer in mind, at first instance, I'd say, you get to this level of thinking, when you do a lot of programming, I was like you, when I started to do programming, thinking, why cant we use multiple variables, when returning multiple values, Hurrah.

Stu Parker
Stu Parker
4,814 Points

Multiple variables can be usefif the info is only one layer deep. Arrays neaten the code and make 2+ layers of information much easier to assemble and disassemble.