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

如何将PHP中的foreach数组循环改写为for循环以分离获取$key与$value

用for循环替代foreach遍历关联数组获取键值对

首先说明原代码的笔误:原代码中foreach循环的遍历目标写为$array,但实际数组变量是$money,这会导致运行报错,需先修正该问题。

修正后的原代码:

<?php
$money = ["Ahmed" => 100, "Sayed" => 150, "Osama" => 100, "Maher" => 250];

// Output
foreach ($money as $key => $value)
{
echo <<<"hello"
The Name Is $key And I Need $value Pound From Him
<br>
hello;
}
?>

由于for循环是基于数字索引的遍历方式,而关联数组没有默认数字索引,我们可以通过两种方式实现替换:

方式一:提取键值到索引数组后遍历

先将关联数组的键名和值分别提取为两个索引数组,再通过for循环的索引匹配对应的键值对:

<?php
$money = ["Ahmed" => 100, "Sayed" => 150, "Osama" => 100, "Maher" => 250];

// 提取键名和值到索引数组
$keys = array_keys($money);
$values = array_values($money);
$arrayLength = count($money);

// for循环遍历输出
for ($i = 0; $i < $arrayLength; $i++) {
    $key = $keys[$i];
    $value = $values[$i];
    echo <<<"hello"
The Name Is $key And I Need $value Pound From Him
<br>
hello;
}
?>

方式二:利用数组指针配合for循环

借助PHP的数组指针函数,模拟foreach的内部遍历逻辑:

<?php
$money = ["Ahmed" => 100, "Sayed" => 150, "Osama" => 100, "Maher" => 250];

$arrayLength = count($money);
// 重置数组指针到第一个元素
reset($money);

// for循环遍历输出
for ($i = 0; $i < $arrayLength; $i++) {
    $key = key($money); // 获取当前指针位置的键名
    $value = current($money); // 获取当前指针位置的值
    echo <<<"hello"
The Name Is $key And I Need $value Pound From Him
<br>
hello;
    next($money); // 将指针移动到下一个元素
}
?>

两种方式都能实现和原foreach循环完全一致的输出效果,前者逻辑直观易读,后者更贴近foreach的底层遍历机制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:12:46