Forum Moderators: coopster

Message Too Old, No Replies

Returning arrays in a function

         

ffoeg

10:23 am on Jul 13, 2007 (gmt 0)

10+ Year Member



Hi all.

I have this really annoying problem in a PHP script. I have a function that checks a number of HTML input fields for errors. When it finds an error, a variable called

$error
that is set to true.

Then, at the end of the script, there is an

if
statement that checks to see if
$error
is true. If it is true, then the function returns false, as well as returning
$error_msg
, which is an array.

The problem I have is that the function does not seem to be returning the array. It returns the false just perfectly, but it refuses to return the array.

I hope this is enough info to work on, and I really appreciate any help.

Thanks*g

tomda

10:49 am on Jul 13, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I may be wrong, but from memory, to return an array using a function, you must do the following

$myarray = myarrayfunction();

ffoeg

11:12 am on Jul 13, 2007 (gmt 0)

10+ Year Member



So what you're saying, is that a variable must be assigned to the function? If that is what you're saying, I have tried that already. It still doesn't seem to work.

RonPK

11:37 am on Jul 13, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If it is true, then the function returns false, as well as returning $error_msg, which is an array.

That's simply not possible: a function cannot return more than one value. Have your function first set $error_msg (use

global
), and then return true and false.

ffoeg

3:19 pm on Jul 13, 2007 (gmt 0)

10+ Year Member



Okaaaay.

So I could use a global

$error_msg
for any error messages, except I must clear it out first when needed.

Would it be possible to maybe just return the array, and then check to see if it exists? So that would mean without returning a false or true.

Thanks for the help :)

coopster

3:41 pm on Jul 13, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You can return a list from a function [php.net].
function myFunction1() 
{
$var = 'MyVariable';
$array = array(
'one' => '001',
'two' => '002'
);
return array($var, $array);
}
list($returnedVar, $returnedArray) = myFunction1();
print '<pre>';
print $returnedVar . "\n";
print_r($returnedArray);
print '</pre>';
exit;

RonPK

3:48 pm on Jul 13, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sure.
$myarray = myarrayfunction(); 
if ($myarray) {
// things seem OK
} else {
// show error message
}

where I said 'return true and false', please read 'return true or false' ...