Forum Moderators: coopster
I'm learning PHP and having "HUGE" difficulties printing an array string out from a function. Here is a bit of the script.
--------
function ValidateMail($Email) {
global $HTTP_HOST;
$result = array();
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $Email)) {
$result[0]=false;
$result[1]="$Email is not properly formatted";
return $result;
}else{
$result[0]=true;
$result[1]="$Email appears to be valid.";
return $result;
} // end of function
---------
echo $result[0];
echo $result[1];
I tried to print it inside and it works. But when I'm trying to print(echo) $result[1] outside the function it doesnt work. Nothing shows up. I tried with "global" command but that didnt work.
Please any good suggestions, been trying to find an answer to this problem for 2 days now and I'm frustrated!
Thanks
global $result;
This is a problem of variable scope. Variables inside functions have nothing to do with variables of the same name outside of the functions - unless you make them global inside the functions.
Also,
return $varname;doesn't do anything in particular at all except for jumping out of the function back to the line of code that called the function, unless you do something like bobnew32 suggests -
$f = ValidateMail($email);
echo $f[0].', '.$f[1];) - or else like what bobnew32's doing, which will use the value returned from the function as the argument of another function and do whatever that function's supposed to do based on this return value. In that case, though, you'd be better off doing
print_r ValidateMail($newstring);since this returns an array, not a regular variable.
I tried ,global $result, but nothing happens. I'm aware of the difference of a string, inside a function and outside of it, and in this case its an array. $result(0,1)and so on.
Im sorry to say that I dont understand your answers and how this new function could solve my problem.
Please can u give me an example on how this should look like. Thanks!
$check = ValidateMail('me@example.com');
function ValidateMail($Email) {
global $HTTP_HOST, $result; /* $result globalized inside function */
$result = array();
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $Email)) {
$result[0]=false;
$result[1]="$Email is not properly formatted";
return $result;
}else{
$result[0]=true;
$result[1]="$Email appears to be valid.";
return $result;
} // end of else
} // end of function
echo $result[0];
echo $result[1];
$resultis globalized inside the function. Will also work if you just
print_r($check), even if you don't globalize
$result(since
$resultis returned, and the return value of the function is assigned to
$check. Hope this helps!
If it doesn't work in your script, it's quite possible you're having other problems with scope. Try it in a separate file and call that file. Try globalizing $result in other places where it may be relevant.