Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not understanding the error I'm getting in my array

Tags:

php

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;
            }
        }
    }
}
like image 940
Yama Avatar asked Oct 15 '25 18:10

Yama


1 Answers

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();
}
like image 130
Barmar Avatar answered Oct 17 '25 09:10

Barmar