PHP新手求助:TypeError错误排查及twoSum代码问题分析
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 returnnullwhen noreturnis specified. Tools like LeetCode's serializer rely on consistent return types. - Check for array keys, not values: Use
isset($array[$key])orarray_key_exists($key, $array)to verify if a key exists. Don't rely on the value being "truthy"—PHP treats0, empty strings, andfalseas 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]is0, which PHP evaluates as false.
内容的提问来源于stack exchange,提问作者Yama

