Can a function return multiple values?
What about multiple arrays, can a function return multiple arrays?
How?
Function returning multiple values? Multiple Arrays?
Moderator: General Moderators
-
superwormy
- Forum Commoner
- Posts: 67
- Joined: Fri Oct 04, 2002 9:25 am
- Location: CT
- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
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
http://www.php.net/manual/en/functions. ... values.php
Mac
a common way in C is to pass pointers to the function, i.e. fgets is defined as 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
char *fgets( char *string, int n, FILE *stream );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
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:-
This didn't work, any ideas?
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);
}
}
?>- twigletmac
- Her Royal Site Adminness
- Posts: 5371
- Joined: Tue Apr 23, 2002 2:21 am
- Location: Essex, UK
Try
and instead of
try
http://www.php.net/manual/en/functions. ... values.php
http://www.php.net/manual/en/language.references.php
Mac
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);
}Code: Select all
return($result);Code: Select all
return $array;But you do have references as volka said:But you don't have pointers in PHP do you?
http://www.php.net/manual/en/functions. ... values.php
http://www.php.net/manual/en/language.references.php
Mac