简体   繁体   中英

PHP get result of function within echo

I want to echo out the result of a function within the initial echo.

echo "<div class='booking-item-rating'>" . stars($hotelSummary[$x]['hotelRating']) . "</div>";

The function:

function stars($stars){
for($i=1;$i<=$stars;$i++) {
    echo "<i class='fa fa-star'></i>";
}
if (strpos($stars,'.')) {
    echo "<i class='fa fa-star-half-empty'></i>";
    $i++;
}
while ($i<=5) {
    echo "<i class='fa fa-star-o'></i>";
    $i++;
}
}

The problem is that the result of the function is printed outside the initial echo field, outside of the div element. How do I get the result of the function to print out within the first echo ?

return that content instead of echoing it:

function stars($stars){
    $string = '';
    for($i=1;$i<=$stars;$i++) {
        $string .= "<i class='fa fa-star'></i>";
    }
    if (strpos($stars,'.')) {
        $string .= "<i class='fa fa-star-half-empty'></i>";
        $i++;
    }
    while ($i<=5) {
        $string .= "<i class='fa fa-star-o'></i>";
        $i++;
    }
    return $string;
}

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