...

View Full Version : Problem with an array in a function



maltrecho
01-24-2004, 01:23 PM
Having the following example, I'm getting all messages correctly when the function isn't called but, why can't I get the messages inside the function when the function is called but I'm still retrieving correctly the variable and the rest of the messages outside the function? What am I doing wrong?


/* my_functions.php */
/* START FUNCTIONS */
function my_function($var,$mess) {
if (bla bla bla) {
do this to $var;
$mess[] = "bla bla bla";
return $var;
} else {
$mess[] = "bla bla bla";
}
/* END FUNCTIONS */
/* my_page.php */
include('my_functions.php');
/*START VALIDATION */
if (bla bla bla) {
do this;
$message[] = "bla bla bla";
} else {
$message[] = "bla bla bla";
}
if (bla bla bla) {
my_function($variable,$message);
$message[] = "bla bla bla";
} else {
$message[] = "bla bla bla";
}
/* END VALIDATION - START OUTPUT */
for ($i = 0; $i < count($message); $i++) {
echo $message[$i];
}
/* END OUTPUT */

Thanks to all.

ReadMe.txt
01-24-2004, 03:54 PM
you'll need to pass the variable by reference:

function my_function($var,&$mess) {

maltrecho
01-24-2004, 08:11 PM
That worked. Thanks a million. Could anybody explain the way it works and why it is handled this way? Is that because it is an array? Thanks.

ReadMe.txt
01-25-2004, 02:56 PM
It's because you are changing the value within the function and not returning it.

Normally variable are passed by value, so a new local variable is created using the values that you passed. Any changes will not affect the original. When you pass by reference you assign the variable inside the function to be another name for the variable that you pass to the function, so any changes to the variable locally will also be performed on the variable passed.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum