85

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?

3

17 Answers 17

118

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'];
Sign up to request clarification or add additional context in comments.

Comments

64

you can do this:

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

print "$a $b $c"; // "abc def ghi"

3 Comments

@GiacomoTecyaPigani list is not a function it's a language construct as stated in the docs.
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.
Since PHP 7.1, you can use [$a, $b, $c] = data();
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

1 Comment

Don't forget that you can also use extract($my_array) to separate the array back into variables: php.net/manual/en/function.extract.php
15

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.

Comments

7

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"
?>

1 Comment

Caution: you may not want to evaluate the function 3 times !
6
$array  = data();

print_r($array);

Comments

6
<?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"];
?>

1 Comment

This code-only answer is pointlessly declaring $arr.
4

Maybe this is what you searched for :

function data() {
    // your code
    return $array; 
}
$var = data(); 
foreach($var as $value) {
    echo $value; 
}

Comments

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,).

1 Comment

Or to access a single value: $b = $dataArray[1];
3

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();

1 Comment

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']?>

Comments

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

Comments

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

Comments

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();

Comments

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.

1 Comment

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.
0

Note that the question is only about getting values from an array, not updating (assigning) values in an array returned by a function. If you assign values into such an array, they go into a local copy of the array, and the original is unchanged. This is a separate problem not addressed here.

The solution is to use the reference operator & twice: once in the function and once in any assignment of its result.

Example:

function &return_array()
   {
   $arr=['a'=>'A'];
   return $arr; // Only a variable can be returned
   }
$arr2=&return_array();
$arr2['a']='B';
// $arr and $arr2 are both now ['a'=>'B'];

Comments

-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.