84

I need to return multiple values from a function, therefore I have added them to an array and returned the array.

<?

function data(){

$a = "abc";
$b = "def";
$c = "ghi";

return array($a, $b, $c);
}


?>

How can I receive the values of $a, $b, $c by calling the above function?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Ajay
  • 1,107
  • 2
  • 13
  • 12
  • 3
    You can acces the values like you access any array. I suggest to read http://php.net/manual/en/language.types.array.php . – Felix Kling Apr 17 '11 at 09:01
  • Effectively a duplicate of https://stackoverflow.com/q/5301065/2943403 – mickmackusa Nov 27 '20 at 22:16
  • While I generally do not encourage potentially polluting the global scope with `extract()`, it can be used in conjunction with `get_defined_vars()` returned from the function. https://3v4l.org/Pb5ul as described in [Destructuring an array using spread operator on left side of assignment to collect all remaining elements in a single variable](https://stackoverflow.com/a/75658700/2943403) – mickmackusa May 03 '23 at 23:09

16 Answers16

117

You can add array keys to your return values and then use these keys to print the array values, as shown here:

function data() {
    $out['a'] = "abc";
    $out['b'] = "def";
    $out['c'] = "ghi";
    return $out;
}

$data = data();
echo $data['a'];
echo $data['b'];
echo $data['c'];
Kristoffer Bohmann
  • 3,986
  • 3
  • 28
  • 35
63

you can do this:

list($a, $b, $c) = data();

print "$a $b $c"; // "abc def ghi"
fredrik
  • 13,282
  • 4
  • 35
  • 52
  • @GiacomoTecyaPigani list is not a function it's a language construct as stated in the [docs](http://php.net/manual/en/function.list.php). – Taylan Nov 11 '14 at 08:31
  • For someone used to Python's tuple unpacking or C++17's structured bindings, this feels like the most natural way by far to return multiple values. – s3cur3 Oct 27 '19 at 18:58
  • 3
    Since PHP 7.1, you can use [$a, $b, $c] = data(); – leninzprahy Apr 20 '21 at 13:12
21
function give_array(){

    $a = "abc";
    $b = "def";
    $c = "ghi";

    return compact('a','b','c');
}


$my_array = give_array();

http://php.net/manual/en/function.compact.php

ITS Alaska
  • 699
  • 1
  • 7
  • 19
  • 4
    Don't forget that you can also use `extract($my_array)` to separate the array back into variables: http://php.net/manual/en/function.extract.php – ITS Alaska May 23 '13 at 17:56
14

The data function is returning an array, so you can access the result of the function in the same way as you would normally access elements of an array:

<?php
...
$result = data();

$a = $result[0];
$b = $result[1];
$c = $result[2];

Or you could use the list() function, as @fredrik recommends, to do the same thing in a line.

Nick
  • 6,967
  • 2
  • 34
  • 56
7
<?php
function demo($val,$val1){
    return $arr=array("value"=>$val,"value1"=>$val1);

}
$arr_rec=demo(25,30);
echo $arr_rec["value"];
echo $arr_rec["value1"];
?>
mohd jagir
  • 71
  • 1
  • 3
6

From PHP 5.4 you can take advantage of array dereferencing and do something like this:

<?

function data()
{
    $retr_arr["a"] = "abc";
    $retr_arr["b"] = "def";
    $retr_arr["c"] = "ghi";

    return $retr_arr;
}

$a = data()["a"];    //$a = "abc"
$b = data()["b"];    //$b = "def"
$c = data()["c"];    //$c = "ghi"
?>
ObiHill
  • 11,448
  • 20
  • 86
  • 135
6
$array  = data();

print_r($array);
Headshota
  • 21,021
  • 11
  • 61
  • 82
4

In order to get the values of each variable, you need to treat the function as you would an array:

function data() {
    $a = "abc";
    $b = "def";
    $c = "ghi";
    return array($a, $b, $c);
}

// Assign a variable to the array; 
// I selected $dataArray (could be any name).
  
$dataArray = data();
list($a, $b, $c) = $dataArray;
echo $a . " ". $b . " " . $c;

//if you just need 1 variable out of 3;
list(, $b, ) = $dataArray;
echo $b;

//Important not to forget the commas in the list(, $b,).
4

Maybe this is what you searched for :

function data() {
    // your code
    return $array; 
}
$var = data(); 
foreach($var as $value) {
    echo $value; 
}
xwlee
  • 1,083
  • 1
  • 11
  • 29
Houssem
  • 6,409
  • 3
  • 18
  • 28
2

All of the above seems to be outdated since PHP 7.1., as @leninzprahy mentioned in a comment.

If you are looking for a simple way to access values returned in an array like you would in python, this is the syntax to use:

[$a, $b, $c] = data();
Douwe
  • 557
  • 7
  • 16
  • A more in-depth explanation of array destructuring: [Destructuring assignment in php for objects / associative arrays](https://stackoverflow.com/q/28232945/2943403) and https://stitcher.io/blog/array-destructuring-with-list-in-php – mickmackusa Jun 24 '22 at 01:18
2

here is the best way in a similar function

 function cart_stats($cart_id){

$sql = "select sum(price) sum_bids, count(*) total_bids from carts_bids where cart_id = '$cart_id'";
$rs = mysql_query($sql);
$row = mysql_fetch_object($rs);
$total_bids = $row->total_bids;
$sum_bids = $row->sum_bids;
$avarage = $sum_bids/$total_bids;

 $array["total_bids"] = "$total_bids";
 $array["avarage"] = " $avarage";

 return $array;
}  

and you get the array data like this

$data = cart_stats($_GET['id']); 
<?=$data['total_bids']?>
Mohamed Badr
  • 59
  • 1
  • 8
1

I think the best way to do it is to create a global var array. Then do whatever you want to it inside the function data by passing it as a reference. No need to return anything too.

$array = array("white", "black", "yellow");
echo $array[0]; //this echo white
data($array);

function data(&$passArray){ //<<notice &
    $passArray[0] = "orange"; 
}
echo $array[0]; //this now echo orange
Khalid
  • 194
  • 1
  • 1
  • 7
1

This is what I did inside the yii framewok:

public function servicesQuery($section){
        $data = Yii::app()->db->createCommand()
                ->select('*')
                ->from('services')
                ->where("section='$section'")
                ->queryAll();   
        return $data;
    }

then inside my view file:

      <?php $consultation = $this->servicesQuery("consultation"); ?> ?>
      <?php foreach($consultation as $consul): ?>
             <span class="text-1"><?php echo $consul['content']; ?></span>
       <?php endforeach;?>

What I am doing grabbing a cretin part of the table i have selected. should work for just php minus the "Yii" way for the db

Erik Leath
  • 85
  • 2
  • 7
1

The underlying problem revolves around accessing the data within the array, as Felix Kling points out in the first response.

In the following code, I've accessed the values of the array with the print and echo constructs.

function data()
{

    $a = "abc";
    $b = "def";
    $c = "ghi";

    $array = array($a, $b, $c);

    print_r($array);//outputs the key/value pair

    echo "<br>";

    echo $array[0].$array[1].$array[2];//outputs a concatenation of the values

}

data();
0

I was looking for an easier method than i'm using but it isn't answered in this post. However, my method works and i don't use any of the aforementioned methods:

function MyFunction() {
  $lookyHere = array(
    'value1' => array('valuehere'),
    'entry2' => array('valuehere')
  );
  return $lookyHere;
}

I have no problems with my function. I read the data in a loop to display my associated data. I have no idea why anyone would suggest the above methods. If you are looking to store multiple arrays in one file but not have all of them loaded, then use my function method above. Otherwise, all of the arrays will load on the page, thus, slowing down your site. I came up with this code to store all of my arrays in one file and use individual arrays when needed.

John
  • 1
  • Why should anyone declare a single-use variable. I would not use this answer. Your sample departs from the OP's data. There are good reasons to not declare an associative array, but the criteria depend heavily on what is going to be done with the returned data. Btw, your function DOES load/populate all of the arrays. – mickmackusa Nov 27 '20 at 11:48
-1

Your function is:

function data(){

$a = "abc";
$b = "def";
$c = "ghi";

return array($a, $b, $c);
}

It returns an array where position 0 is $a, position 1 is $b and position 2 is $c. You can therefore access $a by doing just this:

data()[0]

If you do $myvar = data()[0] and print $myvar, you will get "abc", which was the value assigned to $a inside the function.

JG Estiot
  • 969
  • 1
  • 10
  • 8