How to access the elements of a function's return array?

PhpArraysFunction

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

you can do this:

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

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

Solution 3 - Php

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

Solution 4 - Php

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.

Solution 5 - Php

$array  = data();

print_r($array);

Solution 6 - Php

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

Solution 7 - Php

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

Solution 8 - Php

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;

Solution 9 - Php

Maybe this is what you searched for :

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

Solution 10 - Php

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

Solution 11 - Php

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

Solution 12 - Php

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

Solution 13 - Php

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

Solution 14 - Php

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.

Solution 15 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAjayView Question on Stackoverflow
Solution 1 - PhpKristoffer BohmannView Answer on Stackoverflow
Solution 2 - PhpfredrikView Answer on Stackoverflow
Solution 3 - PhpITS AlaskaView Answer on Stackoverflow
Solution 4 - PhpNickView Answer on Stackoverflow
Solution 5 - PhpHeadshotaView Answer on Stackoverflow
Solution 6 - PhpObiHillView Answer on Stackoverflow
Solution 7 - Phpmohd jagirView Answer on Stackoverflow
Solution 8 - Phpuser3589574View Answer on Stackoverflow
Solution 9 - PhpHoussemView Answer on Stackoverflow
Solution 10 - PhpMohamed BadrView Answer on Stackoverflow
Solution 11 - PhpKhalidView Answer on Stackoverflow
Solution 12 - PhpErik LeathView Answer on Stackoverflow
Solution 13 - PhpLawson ArringtonView Answer on Stackoverflow
Solution 14 - PhpJohnView Answer on Stackoverflow
Solution 15 - PhpJG EstiotView Answer on Stackoverflow