简体   繁体   中英

PHP data not returning but it does on die

I have this code:

    <?php
 function displayList($additional_preferences_list) {
        $output = '<div class="test">';
            foreach($array as $a) {
                $output .= '<div class="testing">'.$a['name'].'</div>';
            }
    ​                
              $output .= '</div>';
              return $output;
}

displayList($additional_preferences_list);
    ?>

If I dd($output); or die the correct values are inputted, multiple testing divs with it's name come out. if I return $output, it is a single testing div without a name. No idea what could be causing this when I die or dd it shows the correct info, if I return or echo it does not.

What am I missing?

TL;DR;

The difference between the response of a function is that "echo" sends something from the server to the client(eg browser), while "return" returns something to the caller. But you are not using function here that's why return $output; showing nothing to you, but if use debugs like return var_dump($output);then you can see the full output of the div string is present there .

return : just exits the execution of the current script.

return returns program control to the calling module. Execution resumes at the expression following the called module's invocation.

If called from within a function , the return statement immediately ends execution of the current function and returns its argument as the value of the function call. return also ends the execution of an eval() statement or script file.

So, You can make a function with those statements and return like below,

<?php
function output(){
    $output = '<div class="test">';
    foreach($array as $a) {
        $output .= '<div class="testing">'.$a['name'].'</div>';
    }
    $output .= '</div>';
    return $output;
}
echo output();
?>

DEMO: https://3v4l.org/sDXDB

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