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
$textInLineinside 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
$textInLinein 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] . ' | '; // 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, ' | '); 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(' | ', $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
相关产品推荐
相关产品推荐

