Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array into a function, and return the results with an array

Tags:

php

So I'm trying to learn how to pass arrays through a function, so that I can get around PHP's inability to return multiple values. Haven't been able to get anything to work so far, but here is my best try. Can anybody point out where I'm going wrong?

function foo($array)
{
    $array[3]=$array[0]+$array[1]+$array[2];
    return $array;
}

$waffles[0]=1;
$waffles[1]=2;
$waffles[2]=3;
foo($waffles);

echo $waffles[3];

For clarification: I want to be able to pass multiple variables into a function, do something, then return multiple variables back out while keeping them seperate. This was just an example I was trying to get working as a work around for not being able to return multiple variables from an array

like image 663
JoeCortopassi Avatar asked Jan 28 '10 23:01

JoeCortopassi


People also ask

How do you pass an array to a function?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

Can you pass an array through a function?

C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.

When you pass an array to a function the function receives?

The address of the first variable is passed when you pass an array to a function in C. An array passed to a function decays into a pointer to its first element.


3 Answers

You seem to be looking for pass-by-reference, to do that make your function look this way (note the ampersand):

function foo(&$array) {     $array[3]=$array[0]+$array[1]+$array[2]; } 

Alternately, you can assign the return value of the function to a variable:

function foo($array) {     $array[3]=$array[0]+$array[1]+$array[2];     return $array; }  $waffles = foo($waffles) 
like image 199
SoapBox Avatar answered Oct 02 '22 19:10

SoapBox


You're passing the array into the function by copy. Only objects are passed by reference in PHP, and an array is not an object. Here's what you do (note the &)

function foo(&$arr) { # note the &
  $arr[3] = $arr[0]+$arr[1]+$arr[2];
}
$waffles = array(1,2,3);
foo($waffles);
echo $waffles[3]; # prints 6

That aside, I'm not sure why you would do that particular operation like that. Why not just return the sum instead of assigning it to a new array element?

like image 23
Tor Valamo Avatar answered Oct 02 '22 19:10

Tor Valamo


function foo(Array $array)
{
     return $array;
}
like image 38
user2587105 Avatar answered Oct 02 '22 19:10

user2587105