Forum Moderators: coopster

Message Too Old, No Replies

Returning 2 values from one function

is it possible?

         

neophyte

7:06 pm on Jun 10, 2005 (gmt 0)

10+ Year Member



I've got a function that does all my db selecting, inserting, updating and deleting. Very common.

Only a select query returns anything: the selected recordSet.

Since I frequently need the number of rows from a table AS WELL as all the records from a table, I'd like to set up this function that return both values by default.

Maybe like:

...function code...
return $recordSet;
return $tableRows;

where mysql_num_rows($recordSet) would be a part of the function, rather than after the function call.

If that would work, the bigger question is how do I "catch" two returned values from a single function call? By settin up both the function and the call to load and deliver an array? Like:

...function code...
$array[recordSet] = mysql_query($query, $db);
$array[rows] = mysql_num_rows($array[recordSet]);
return $array;

which would be called like:

$array = dbQuery($query, TRUE);

Then I could just pick apart the array when and where I need it in the page?

Has anyone done this before?

Neophyte

coopster

7:24 pm on Jun 10, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



That's exactly [php.net] how it is done. Passed in arrays.

Blackie

10:54 pm on Jun 10, 2005 (gmt 0)

10+ Year Member



Or make a variable global, so that you can change its value inside function and see the changes outside.

leadegroot

7:48 am on Jun 12, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



or make it part of an object, so it sets object values, rather than returning a value (commonly you return a success/failure flag, but set the results into object fields)

mcibor

1:57 pm on Jun 13, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



As coop mentioned put in into array, or pass by reference (NEVER BY GLOBAL). Globals are very tricky because you may easily loose control of them.

array:

function double($a){
return array($a * $a, $a + $a);}

$a = 3;
$ans = double($a);// answer = array(9, 6);

reference:

function double($a, $b){
$b = $a + $b;
return $a * $b;}

$a = 3; $b = 2;
$a = double($a, $b);// a = 6; b = 2;
$a = double($a, &$b);// a = 48; b = 8; - reference - b is changed as well

Hope this helps
Michal Cibor