I'm new to PHP and hope people can help me get a better insight. I'm trying to resolve a problem I did in JS into PHP to better understand the syntax and am running to this error:
PHP fatal error: uncaught TypeError: Argument 1 passed to Serializer::serializeArray() must be of type array, null given, called in /leetcode/precomiled/serializer.php
This is my code. I hope someone can tell me what I'm doing wrong to better understand and avoid further PHP mistakes. Thank you to all who answer.
class Solution {
function twoSum($nums, $target) {
$collection = array();
foreach($nums as $key => $num) {
$subtracted = $target - $num;
if ($collection[$subtracted]) {
return array($collection[$subtracted], $key);
} else {
$collection[$num] = $key;
}
}
}
}
Your function doesn't work correctly when the pair of numbers includes the first element of the array. You use:
if ($collection[$subtracted])
to test if $subtracted
is a key of the array. But if the value of $collection[$subtracted]
is 0
, that will also fail the if
test. Change that to:
if (isset($collection[$subtracted]))
You should also add:
return array();
after the for
loop, so that it returns an empty array by default if no matching elements are found.
function twoSum($nums, $target) {
$collection = array();
foreach($nums as $key => $num) {
$subtracted = $target - $num;
if (isset($collection[$subtracted])) {
return array($collection[$subtracted], $key);
} else {
$collection[$num] = $key;
}
}
return array();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With