为什么退货没有';在我的函数代码中不起作用,但echo在php中起作用


Why return didn't work inside my function code, but echo works, php?

看看我的代码,如果我使用echo$html_of_questions,它是有效的。如果我使用return,它就不起作用。为什么?我应该只使用echo吗?因为有人告诉我应该在函数中始终使用return。

<?php
function fruit($fruit){
$questions = [
         'q1' => '<div>Is it good?</div>
                 <input type="text" value="submit"/>',
         'q2' => '<div>where is it from?</div>
                 <input type="text" value="submit"/>',
       ];
$fruit_questions = [
         'apple'  => [1,3,5],
         'banana' => [1,2,4],
         'guava' => [17,21,4],
       ];
$question_keys = $fruit_questions[$fruit];
$html_of_questions = ''; // This will hold the questions to echo
foreach($question_keys as $question_key){
    $html_of_questions .= $questions['q'.$question_key]
}
     return $html_of_questions;//doesn't work, use echo it works
}
     fruit('apple');
?>

它是有效的,你只是不需要对结果做任何事情:

fruit('apple');

如果你想回显结果,你必须回显它:

echo fruit('apple');

或者可能将其存储在一个变量中,然后对其进行处理:

$result = fruit('apple');
// other code
echo $result;

仅仅调用一个函数并不会告诉系统对该函数的结果做任何事情。该函数只是封装一个操作并返回一个结果。然后你必须对结果采取措施。