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

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?

This question is related to php arrays function

The answer is


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

you can do this:

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

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

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;

Maybe this is what you searched for :

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

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.


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

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.


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.


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


$array  = data();

print_r($array);

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


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

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

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

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

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers