How to echo a function response in php
Solution:
If you did
$chk_str = chk_string($string);
then you could echo $chk_str;
.
The $chk_str
you are trying to echo is only visible in your function.
More description:
Your function (chk_string) is in a different scope than your echo.
Your function returns a variable, but that variable is "lost", since you don't assign it to another variable.
Your code currently does something like this line by line:
Your function declaration
$string means "this is just a test"
your functions result as a string, just floating in the code
write out a variable that doesn't exist.
I hope this helped in someway.
Answer
Solution:
You need to store returned value in a particular variable if you want to echo that variable like this,
$chk_str = chk_string($string) ;
echo $chk_str;
Another way you can just directly echo returned value like this,
echo chk_string($string) ;
Answer
Solution:
Your question is about variable scope and it is answered already, but I would recommend you to take a look at variable scope here https://www.php.net/manual/en/language.variables.scope.php.
Basically, every variable has its scope and we can not access a variable outside its scope. In your case, scope of variable $chk_str
is inside function chk_string
so you can not access it outside of the function. Because you return value of $chk_str
in function chk_string
so you still can access its value through response of function chk_string
, for example:
echo chk_string('a string');
OR
$result = chk_string('a string');
echo $result;
Source