How do I correct this filecount?

You’re right – this is very much a generic PHP question. But fwiw, the issue is that you clearly want to count all JPEG files, but your sample code counts all files – so…

while ( false !== $f = $d->read() ) {
    if ( in_array( strtolower( pathinfo( $f, PATHINFO_EXTENSION ) ), [ 'jpg', 'jpeg' ] ) )
        $filecount++;
}