【问题标题】:how inserting foreach loop all final result in a variable in php?如何在 php 中插入 foreach 循环所有最终结果?
【发布时间】:2015-08-28 11:52:01
【问题描述】:

如何在 php 中插入 foreach 循环所有最终结果。

例如我有三个数组:

$myarray = ('a','b','c');
foreach($myarray as $myarray){
$text = $myarray;
}
echo $text;//i want echo abc but this code only print c.

我希望将所有最终代码打印成类似 $text 并回显一个循环。

我知道这段代码很好用,但我希望所有结果都在循环之外

$myarray = ('a','b','c');
foreach($myarray as $myarray){
$text = $myarray;
echo $text;
}

请帮忙。

提前感谢所有朋友。

【问题讨论】:

  • 谷歌:PHP implode()

标签: php foreach


【解决方案1】:

这可能是您正在寻找的:

<?php
$myarray = ('a','b','c');
$text = '';
foreach($myarray as $element){
  $text .= $element;
}
echo $text;

另一种选择是这样的:

<?php
$myarray = ('a','b','c');
echo implode('', $myarray);

【讨论】:

  • 非常非常感谢。我想要这样的代码,它能够从 foreach 循环中回显最终结果,而不是在 foreach 循环中。非常非常感谢。
【解决方案2】:
$text = [];
$myarray = ['a','b','c'];
foreach($myarray as $element) {
  $text[] = $element; // append a new element to the array $text
  // ok, kinda useless since $text==$myarray after the loop
  // but ....it's only an example
}
echo join(', ', $text); see // http://docs.php.net/join

【讨论】:

    【解决方案3】:

    你需要implode():

    <?php
    $myarray = ('a','b','c');
    echo implode('', $myarray);
    

    Documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 2015-09-18
      • 2012-12-20
      • 2019-07-25
      • 1970-01-01
      相关资源
      最近更新 更多