Php - Foreach返回一个值,第一个或最后一个值 [英] Php - Foreach returning one value, first or last

查看:366
本文介绍了Php - Foreach返回一个值,第一个或最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在函数中使用return,我将只获得一个值。

如果使用echo,我将得到所有的值。

  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)。'';






$ b看起来我不能将回声插入数据库,如果我运行该功能,它们显示为空白。
怎么办?

解决方案

当您有 return 代码不会进一步执行。生成整个数据,然后返回那个数据。

你可以构建一个数组。就像 - $ / $>

  $ url = array(); 
foreach($ matches [0]为$ matchbun)
{
.....
$ urls [] = ucfirst($ url_final);
}
返回$ url;

或者您可以生成一个字符串。喜欢 -

  $ url =''; 
foreach($ matches [0]作为$ matchbun)
{
.....
$ url。= ucfirst($ url_final);
}
返回$ url;


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?

解决方案

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;

这篇关于Php - Foreach返回一个值,第一个或最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆