How to Return Multiple Values from Functions in PHP
In this lesson we will look at how to return multiple values from functions in PHP.
Consider this simple function which adds 2 numbers together and returns the result:
You can find more details about the above simple function in this article.
Now, what if we wanted to add, subtract, and multiply 2 numbers and return the 3 answers.
In order to do this we can use an array and store the 3 answers in the array as follows:
Line 3: we have a function called calculate and it accepts 2 arguments which we are assigning to variables $number1 and $number2
Line 5: we are adding the 2 numbers and assigning the answer to $add
Line 6: we are subtracting the 2 numbers and assigning the answer to $subtract
Line 7: we are multiplying the 2 numbers and assigning the answer to $multiply
Line 8: we are returning an array with the 3 answers
Line 12: we print the returned array after called the calculate function with arguments 3 and 5
The output will look like this:
We can see the 3 answers from adding, subtracting and multiplying 3 and 5.
In order to output the results in a nicer way we could do something like this:
The output would be:
We could even create a loop and do something like this:
The important thing to remember is that the array position starts at 0, not 1.
On line 13 I have declared another array to store the operators.
On line 16 I have started a simple loop to go through each of the answers and echo out the results. This works because I know what operators are in the function.
The are many other ways we could approach this problem...but, why make things more complicated than they need to be!