Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unnecessary EmptyArrayAccess after checking if key exists #7120

Closed
GeorgeCadwallader opened this issue Dec 10, 2021 · 5 comments
Closed

Unnecessary EmptyArrayAccess after checking if key exists #7120

GeorgeCadwallader opened this issue Dec 10, 2021 · 5 comments

Comments

@GeorgeCadwallader
Copy link

https://psalm.dev/r/b4217d10dd

@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/b4217d10dd
<?php

$testing = [];

if (array_key_exists('a', $testing)) {  
    $a = $testing['a'];
}
Psalm output (using commit 4ac0b64):

ERROR: EmptyArrayAccess - 6:10 - Cannot access value on empty array variable $testing

INFO: MixedAssignment - 6:5 - Unable to determine the type that $a is being assigned to

INFO: UnusedVariable - 6:5 - $a is never referenced or the value is not used

@weirdan
Copy link
Collaborator

weirdan commented Dec 10, 2021

The code, as presented, is pointless, as if won't be ever entered. Do you have a more realistic example of where you have this issue?

@AdeAttwood
Copy link

@weirdan I think there maybe something different with our setup to the playground. The test code we were working with is

<?php

/** @return array<array-key, string> */
function get_array(): array { return []; }
function get_string(): string { return 'a'; }

function get_int(): int {
    /** @psalm-trace $array */
    $array = get_array();
    /** @psalm-trace $counts */
    $counts = array_count_values($array);
    
    if (array_key_exists(get_string(), $counts)) {
        return $counts[get_string()];
    }
    
    return 0;
}

Both environments give the same type for $array of array<array-key, string> however $counts is giving different types the playground is array<array-key, positive-int> however in our environment its array<empty, empty>.

We are on PHP 8.0 and vimeo/psalm v4.15.0. I don't know if the playground is using the master branch or its using a tagged version.

For now we can fix our code by adding a var comment to the differing type and that seems to be a acceptable work around for us.

@weirdan
Copy link
Collaborator

weirdan commented Dec 13, 2021

Playground is running dev-master. The difference you see is due to #7115 (not yet a part of any release).

@AdeAttwood
Copy link

@weirdan thank you, I have run our code on dev-master and that has fixed the issue. This will be resolved in the next release 👍

@orklah orklah closed this as completed Dec 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants