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

PHP新手求助:TypeError错误排查及twoSum代码问题分析

Fixing Your twoSum PHP Code & the Serialization Error

Hey there! As a fellow PHP learner, I totally get how frustrating these little syntax/logic gaps can be when switching from JS. Let's walk through what's causing that error and fix your code step by step.

First, Why That Fatal Error Happens

The error says Serializer::serializeArray() got null instead of an array. That's because your function doesn't return anything if no pair is found (even though LeetCode's twoSum problem guarantees a solution, PHP functions default to returning null when there's no explicit return statement). The serialization tool expects an array, so it throws a type error when it gets null.

Next, The Logic Bug in Your Code

Looking at your loop:

if ($collection[$subtracted]) {
    return array($collection[$subtracted], $key);
}

This checks if the value of $collection[$subtracted] is "truthy" in PHP. But if the matching index is 0 (e.g., the first element in $nums is part of the solution), PHP will treat 0 as false, and your code will skip the correct match. That's a common gotcha when coming from JS!

Fixed Code

Here's the corrected version with explanations:

class Solution {
    function twoSum($nums, $target) {
        $collection = array();
        foreach($nums as $key => $num) {
            $subtracted = $target - $num;
            // Use isset() to check if the key exists, not the value's truthiness
            if (isset($collection[$subtracted])) {
                return array($collection[$subtracted], $key);
            }
            $collection[$num] = $key;
        }
        // Add an explicit return even if the problem guarantees a solution
        // This prevents the function from returning null
        return array();
    }
}

Key Takeaways to Avoid Future Errors

  • Always return explicitly: Unlike JavaScript (which returns undefined), PHP functions return null when no return is specified. Tools like LeetCode's serializer rely on consistent return types.
  • Check for array keys, not values: Use isset($array[$key]) or array_key_exists($key, $array) to verify if a key exists. Don't rely on the value being "truthy"—PHP treats 0, empty strings, and false as falsy, even if the key is valid.
  • Test edge cases: For example, test with $nums = [0,4,3,0] and $target = 0—your original code would miss the pair [0,3] because $collection[0] is 0, which PHP evaluates as false.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:03:53