在 PHP 中返回数组的多个值

$array = [

  'H',

  'E',

  'L',

  'L',

  'O',

];

这是我的阵列。我想像这样打印这个数组:


H

HE

HEL

HELL

HELLO

我想动态地执行此操作。例如,编写一个函数来接收数组并对该数组执行此操作。任何数组都是可能的。


一只名叫tom的猫
浏览 113回答 2
2回答

翻过高山走不出你

您可以使用嵌套for循环来打印模式,如下所示:$array = [&nbsp; &nbsp; &nbsp;'H',&nbsp; &nbsp; &nbsp;'E',&nbsp; &nbsp; &nbsp;'L',&nbsp; &nbsp; &nbsp;'L',&nbsp; &nbsp; &nbsp;'O',];echo printPattern($array);function printPattern($array){&nbsp; &nbsp; &nbsp;$ret = '';&nbsp; &nbsp; &nbsp;for($i = 0; $i < count($array); $i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $str = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for($j = 0; $j < $i+1; $j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$str .= $array[$j];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $ret .= $str.'<br>';&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;return $ret;}

qq_花开花谢_0

将数组转换为字符串,然后迭代字符串的长度(要么对数组进行计数,要么使用strlen(),它们将是相同的)并使用substr()来获取给定的长度,该长度将与迭代的次数相同。$array = [&nbsp; 'H',&nbsp; 'E',&nbsp; 'L',&nbsp; 'L',&nbsp; 'O',];$string = implode("", $array);for ($i = 0; $i <= count($array); $i++) {&nbsp; &nbsp; echo substr($string, 0, $i)."\n";}现场演示https://3v4l.org/ibXpK
打开App,查看更多内容
随时随地看视频慕课网APP