phppsalm-php

How to type loop that iterates over an array of mixed


Given this code (https://psalm.dev/r/156e52eb66):

<?php

function keys(): array
{
  return ['foo', 'bar'];
}

// no lines above can be changed

foreach (keys() as $k) {
  echo gettype($k);
}

how would one type it assuming the keys function is not under our control (in a different project) and it effectively returns an array of mixed (array<array-key, mixed>).

So, one may only change the loop and around it.

Is it even possible?

UPD: I reported https://github.com/vimeo/psalm/issues/2025


Solution

  • If I get it right this might help you:

    foreach (array_keys(keys()) as $k) {
     echo gettype(keys()[$k])."\n";
    }