Page 1 of 1

Function returning multiple values? Multiple Arrays?

Posted: Thu Oct 10, 2002 8:15 am
by superwormy
Can a function return multiple values?

What about multiple arrays, can a function return multiple arrays?

How?

Posted: Thu Oct 10, 2002 8:20 am
by twigletmac
A function can only return one value, that value can be a number, a string, an array etc. If you want to return multiple values you have to return them in an array whether they are strings or already arrays themselves.

http://www.php.net/manual/en/functions. ... values.php

Mac

Posted: Thu Oct 10, 2002 8:33 am
by volka
a common way in C is to pass pointers to the function, i.e. fgets is defined as

Code: Select all

char *fgets( char *string, int n, FILE *stream );
it will write up to n characters in the buffer specified by string.
You may do the same in PHP by passing references to the function, i.e.

Code: Select all

<?php
function division($a, $b, &$remainder)
{
	$remainder = $a % $b;
	return (int)($a / $b);
}
print(division(5, 3, $remainder));
print(' remainder: '.$remainder);
?>
  • but you should
  • consider passing it back in a array
  • clearly mark it if you're using a reference and going to change the parameter's value
p.s.: & replaced by & in php-section :cry:

Posted: Thu Oct 10, 2002 9:40 am
by Takuma
But you don't have pointers in PHP do you?
Anyway I was having trouble with returning an array but here was my problem.

I had made an MySQL Function library. I wanted to return a value fgrom the db using mysql_fetch_array(). The query will return multipl rows. And I tried to put it into an array. Like this:-

Code: Select all

<?php
class class_mysql {
  function execute($sql,$option) {
    switch ($option) {
      case 1:
        $temp = mysql_query($sql);
        $i = 0;
        while(list($result) = mysql_fetch_array($temp)) {
          $arrayї$i] = $result;
        }
    }
    return($result);
  }
}
?>
This didn't work, any ideas?

Posted: Thu Oct 10, 2002 9:49 am
by twigletmac
Try

Code: Select all

$temp = mysql_query($sql);
$num_rows = mysql_num_rows($temp);
for ($i = 0; $i < $num_rows; $i++) {
    $arrayї$i] = mysql_fetch_array($result);
}
and instead of

Code: Select all

return($result);
try

Code: Select all

return $array;
But you don't have pointers in PHP do you?
But you do have references as volka said:
http://www.php.net/manual/en/functions. ... values.php
http://www.php.net/manual/en/language.references.php

Mac