Reputation: 43
function foo() {
$foo1= mysql_query();
$db_field = mysql_fetch_assoc($foo1);
$word= $db_field['word'];
$lower=strtolower($word);
}
foo();
print $lower;
The function above executes a block of code with the endgame being the $lower
variable, which is the lowercase of a word from a database. As the code is written above, I get an error saying that $lower is not defined
.
I tried returning $lower
with return $lower
, but that didn't work. How do I keep a variable from a function for later use?
Upvotes: 0
Views: 41
Reputation: 76
put your return statement back
...
return $lower;
}
$result = foo();
print $result;
Upvotes: 0
Reputation: 656
You could actually use 'global' Like This.
$lower = '';
function foo() {
global $lower;
$foo1= mysql_query();
$db_field = mysql_fetch_assoc($foo1);
$word= $db_field['word'];
$lower=strtolower($word);
}
foo();
print $lower;
Upvotes: 0
Reputation: 2819
$lower
variable used only in the function. it can't work out of the function. Do like this,
function foo() {
$foo1= mysql_query();
$db_field = mysql_fetch_assoc($foo1);
$word= $db_field['word'];
$lower=strtolower($word);
return $lower;
}
$lower = foo();
print $lower;
Upvotes: 0
Reputation: 8369
$lower
is defined inside the function which have scope only within that function. So trying to access it outside the function will definitely cause proble. You have to return it in the function .Try with :
function foo() {
$foo1= mysql_query();
$db_field = mysql_fetch_assoc($foo1);
$word= $db_field['word'];
return strtolower($word); // return the value
}
$lower=foo(); // this will contain the return value of foo()
print $lower;
Upvotes: 0
Reputation: 3953
First of all, return $lower
at the end of the function is correct. Then you use:
$var = foo();
You just discoverd the scope of a variable. $lower
is only availible inside the function, so you cant use it outside of it.
Upvotes: 1