How to Return Multiple Values from a Function in PHP

How to return multiple values from a function in PHP.  Is it possible to return more than one values when calling a function. This type of question is mostly asked by beginners who just started coding.  Do i have to use multiple return statements for returning multiple values.

** Remember function cannot return multiple values but you can return multiple values from a function using an array.

In this article, i’ll explain how to return multiple values from a function using array. Return statement can only return single value at a time. And only one return statement can be used inside a function. So let’s check how to return multiple values.

How to install PHP, MySql, Apache in Ubuntu.

How to Return Multiple Values from a Function in PHP

Inside a function values are returned by using return statement. After return statement function end its execution immediately and pass control back to the line from which it was called.

If you want to return multiple values in PHP then make an array and return it.

NOTE – Only single return statement is used inside a function. You can’t use multiple return statement inside a function to return multiple values.

Shorter Syntax of Array Declaration in PHP 5.4 .

Seems confusing, let’s understand this concept through example.

1. First Example – Return multiple values in the form of array.

2. Second Example – Returning values in the form of associative array.

Check if value exists in array.

3.

Using compact() Function in PHP to return multiple values

compact() method create array containing variables and their values.

How to Retrieve Multiple Values in PHP

We learned how to return multiple values from function in php through arrays. Now next important thing is how to retrieve those values.

1. Using list() method –

list() is a language construct. list() is used to assign a list of variables in one operation. Through list function(), you can assign array items to variables.

Top five most used PHP functions .

2. Second approach is to retrieve values using their indexes.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.