简体   繁体   中英

How to echo a function response in php

I created a function to check for special characters in a string, but I can't seem to get it to echo the response message

Here is my code

<?php
    function chk_string($string){
        if (preg_match('/[\^£$%&*()}{@#~?><>|=_+¬-]/', $string))
        {
            $chk_str="false";
        } else {
            $chk_str="true";
        }
        return $chk_str;
    }
    
$string="this is just a test" ;
chk_string($string) ;
echo $chk_str;
?>

The "echo $chk_str" is not echoing anything.

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) ;

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM