PHP没有ArrayList,仅用array;调试推荐print_r()或var_dump();格式化输出可用str_pad()、json_encode(JSON_PRETTY_PRINT)等。

PHP里没有ArrayList,只有array
Java开发者常搜“ArrayList”,但PHP原生不支持这个类名——它用的是array。直接写new ArrayList()会报错:Fatal error: Class 'ArrayList' not found。如果你在框架(如Laravel)里看到类似结构,那也是封装后的对象,底层仍是数组或Traversable接口实现。
用print_r()或var_dump()快速看数组结构
调试时最常用、最省事的方式就是直接输出结构。区别在于:
-
print_r($arr):人眼友好,不显示数据类型,适合简单查看嵌套关系 -
var_dump($arr):显示类型和长度(比如string(5) "hello"),适合排查类型错误
加echo '<pre class="brush:php;toolbar:false;">'</code>可让缩进对齐(避免浏览器自动合并空白):</p>
<pre class="brush:php;toolbar:false;">echo '<pre class="brush:php;toolbar:false;">';
print_r($arr);
echo '</pre>';
<h3>foreach循环打印时控制格式对齐</h3>
<p>如果要“整齐打印”,关键不是循环本身,而是输出时的排版控制。常见需求有:</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill6494" title="Feishu calendar sync, local ics to json data for AI agent"><img
src="https://img.php.cn/upload/skill/000/000/081/179099469998654.jpg" alt="Feishu calendar sync, local ics to json data for AI agent" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill6494" title="Feishu calendar sync, local ics to json data for AI agent">Feishu calendar sync, local ics to json data for AI agent</a>
<p>将ICS日历文件转为JSON格式,用于飞书日历导入导出及数据集成。</p>
</div>
<a href="/xiazai/skill6494" title="Feishu calendar sync, local ics to json data for AI agent" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p>
<ul>
<li>键值对左对齐(如<code>id......1)→ 用sprintf()或str_pad()
json_encode($arr, JSON_PRETTY_PRINT)(PHP ≥ 5.4)示例:固定宽度键值对
$arr = ['name' => 'Alice', 'age' => 28, 'city' => 'Shenzhen'];
foreach ($arr as $key => $value) {
echo str_pad($key, 10) . ': ' . $value . "\n";
}
// 输出:
// name : Alice
// age : 28
// city : Shenzhen
嵌套数组遍历时容易忽略引用和深度限制
多维数组用foreach递归遍历,但要注意:
- 直接
foreach($arr as $v)只处理一层,深层需手动递归或用RecursiveArrayIterator - 修改数组内容时,若需改原数组,必须写
foreach($arr as &$v)(加&),否则是副本 -
print_r()默认递归深度为10,超深数组会被截断,可传第二个参数true并配合ini_set('xdebug.var_display_max_depth', 20)调整(仅开发环境)
真正整齐的嵌套输出,往往得靠json_encode(..., JSON_PRETTY_PRINT)或专门的调试工具(如Symfony VarDumper),而不是手写循环。


















