You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP初学者求助:实现数组每行显示4个元素(附代码)

Fixing Your PHP Array Display (4 Elements Per Line)

Hey there! I see you're trying to display your array with 4 elements per line, and your current code has a couple of small issues that are keeping it from working right. Let's walk through the fixes and even show a simpler way to do this.

What's Wrong With Your Current Code?

  • You're using '/n' for line breaks, but in HTML, browsers don't recognize that—you need to use the <br> tag instead.
  • You're echoing $textInLine inside the loop and again outside, which leads to duplicate output, and the final echo only shows the last line's content.
  • The way you're assigning $textInLine in each loop iteration is overwriting it instead of building up the full string.

Fixed Version of Your Original Code

Let's adjust your code to work correctly:

<?php 
$arry = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$nr_elm = count($arry); // Get total number of elements
$nr_col = 4; // Elements per line

if ($nr_elm > 0) {
    $textInLine = ''; // Initialize an empty string to build our output
    for($i = 0; $i < $nr_elm; $i++) {
        // Add the current element and separator to the string
        $textInLine .= $arry[$i] . '&nbsp;|&nbsp;';
        
        // Add a line break when we hit the end of a row
        if(($i + 1) % $nr_col === 0) {
            $textInLine .= '<br>';
        }
    }
    // Optional: Remove the trailing separator from the end of the last line
    $textInLine = rtrim($textInLine, '&nbsp;|&nbsp;');
    echo $textInLine; 
}
?>

A Simpler Approach Using Built-in PHP Functions

PHP has a handy function called array_chunk() that splits your array into smaller chunks of the size you want. This makes the code much cleaner:

<?php 
$arry = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
// Split the array into groups of 4 elements each
$rowGroups = array_chunk($arry, 4);

// Loop through each group and display the elements with separators
foreach($rowGroups as $row) {
    echo implode('&nbsp;|&nbsp;', $row) . '<br>';
}
?>

This method is easier to read and maintain—no manual counting needed!

Either approach will give you the result you want: 4 elements per line, separated by |.

内容的提问来源于stack exchange,提问作者Mukesh Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:12:28