Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php - Foreach returning one value, first or last

If I use return in my function, I will get only one value.

If I use echo, I get all the values. I don't get it.

foreach($matches[0] as $matchbun)
{

        $var1 = str_split($matchbun, 34);
        $replace_line = "-";
        $var_final = str_replace($replace_line, " ", $var1[1]);

        $replace_url = array('google.com', '/name/');
        $replace_url_with = array('yahoo.com', '/url_');
        $url_final = str_replace($replace_url, $replace_url_with, $matchbun);



        return ''.ucfirst($url_final).'';

}

Seems that I can't insert the echoes into a database, they appear blank if I run the function. What to do?

like image 843
Cristi B Avatar asked Aug 24 '26 19:08

Cristi B


1 Answers

When you have a return the code would not execute further. Generate the whole data, then return that data.

You can either built an array. Like -

$urls= array();
foreach($matches[0] as $matchbun)
{
    .....
    $urls[]= ucfirst($url_final);
}
return $urls;

Or You can generate a string. Like -

$urls= '';
foreach($matches[0] as $matchbun)
{
    .....
    $urls.= ucfirst($url_final);
}
return $urls;
like image 97
Sougata Bose Avatar answered Aug 27 '26 08:08

Sougata Bose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!