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

PHP数组中整数1倒数第三次出现的索引查找异常排查

Fixing the Third-to-Last Occurrence of 1 in Your PHP Array

Hey there! Let's get this sorted out. Your array $arr = array(2, 3, 1, 4, 5, 6, 1, 1,10,11,12,1) has four instances of the integer 1, at indices 2, 6, 7, and 11. The reason your code is outputting 11 is almost certainly because it's tracking the last occurrence of 1 instead of the third-to-last one.

Let's look at two reliable solutions to get the correct index (6):

Solution 1: Collect all indices of 1, then pick the third-to-last

This approach is straightforward—first we gather every index where 1 appears, then we check if there are at least 3 occurrences, and grab the one that's three positions from the end of our collected list:

$arr = array(2, 3, 1, 4, 5, 6, 1, 1, 10, 11, 12, 1);
$onesIndices = [];

// Loop through the array and collect all indices where value is 1
foreach ($arr as $index => $value) {
    if ($value === 1) {
        $onesIndices[] = $index;
    }
}

// Check if we have enough occurrences to get the third-to-last
if (count($onesIndices) >= 3) {
    $thirdLastIndex = $onesIndices[count($onesIndices) - 3];
    echo $thirdLastIndex; // Outputs 6
} else {
    echo "Not enough occurrences of 1 in the array!";
}

Solution 2: Traverse the array from the end (more memory-efficient)

If you're working with large arrays, this method saves memory because we don't need to store all indices—we just count backwards until we hit the third 1:

$arr = array(2, 3, 1, 4, 5, 6, 1, 1, 10, 11, 12, 1);
$count = 0;
$targetIndex = -1;

// Start from the last element and move backwards
for ($i = count($arr) - 1; $i >= 0; $i--) {
    if ($arr[$i] === 1) {
        $count++;
        // Stop as soon as we find the third occurrence from the end
        if ($count === 3) {
            $targetIndex = $i;
            break;
        }
    }
}

if ($targetIndex !== -1) {
    echo $targetIndex; // Outputs 6
} else {
    echo "Not enough occurrences of 1 in the array!";
}

Why your original code failed

Chances are your original code was looping from the start of the array, updating a variable every time it found a 1. That would leave you with the last occurrence (index 11) instead of the third-to-last. By either collecting all indices or counting backwards, we ensure we target the correct position.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:10:11