SoFunction
Updated on 2025-03-02

How to recursively use php function and the difference between return and echo


<?php
//Simulate SQL data
$array = array(0=>'apple',1=>'banana',2=>'cat',3=>'dog',4=>'egg','5'=>'father');

//function Usage 1
//arr is the incoming data $con is the condition
function f_1($arr,$con){
//The array here is private in this function and will not conflict with the array that appears
//So, if the array on the outside is not inside, it cannot be used directly on the inside.
//Instance an array first
$array = array();
//For foreach while usage is similar, specific baidu
foreach ($arr as $key => $value) {
//If the value of the loop is equal to con, add it to the array
if ($value == $con) {
//The difference between an array and a variable is that it has added a []
$array[] = array($key => $value);
}
}
//After the loop gets the result, return to the array. So, this function is an array
return $array;
//The return is terminated after execution, and no matter what code there is behind it, it will not be executed
//Return can be regarded as the end of a function
}


//function Usage 2
//$con can be an array
function f_2($arr,$con){
//Instance a variable first
$code = '<ul>';
foreach ($arr as $key => $value) {
//The for loop inside is to loop out the con content
foreach ($con as $value2) {
// .= Add more to the future Continuously define variables
// If the value that the data loops out of the first layer is the same as the value that the condition loop of the second layer is added to the variable
// Multiple for loops to filter data is also called recursion
if ($value == $value2) {
$code .= '<li>'.$value.'</li>';
}
}
}
$code .= '</ul>';
//After the loop gets the result, return the variable. So, this function is a string
return $code;
}

//function Usage 3
//What is the difference between echo and return in the function? It depends on the execution result
function f_3($arr,$con){
//Instance a variable first
echo '<ul>';
foreach ($arr as $key => $value) {
//The for loop inside is to loop out the con content
foreach ($con as $value2) {
// .= Add more to the future Continuously define variables
// If the value that the data loops out of the first layer is the same as the value that the condition loop of the second layer is added to the variable
// Multiple for loops to filter data is also called recursion
if ($value == $value2) {
echo '<li>'.$value.'</li>';
}
}
}
echo '</ul>';
}
?>

f_1 output start<br/>
<?php
//Because f_1 is an array, we can print it out
print_r(f_1($array,'banana'));
?>
<br/>f_1 output end
<hr/><br/>
f_2 output start<br/>
<?php
//f_2 is a variable
$con = array('apple','father');
echo f_2($array,$con);
?>
<br/>f_2 output end
<hr/><br/>
f_2 output start<br/>
<?php
//f_3 has already echoed in the function, so you don't need to echo when executing the function
$con = array('apple','father');
f_3($array,$con);
?>
<br/>f_2 output end