Skip to content

Stop to automatically cast numeric-string to int when using them as array-key #7845

@VincentLanglet

Description

@VincentLanglet

Description

Currently we have

$a = ['01' => '01', '10' => '10'];

var_dump($a);
// (string) 01 => (string) 01
// (int) 10 => (string) 10
 
var_dump(array_flip($a));
// (string) 01 => (string) 01
// (int) 10 => (int) 10

var_dump(array_flip(array_flip($a)));
// (string) 01 => (string) 01
// (int) 10 => (int) 10

var_dump($a === array_flip(array_flip($a))); // false

Is there a reason to do this automatic cast from '10' to 10 when it's an array-key or wouldn't it be better to change this behavior for PHP 9 ?

To me it causes unexpected result like this one:

<?php

declare(strict_types=1);

function foo(string $string) {}

$array = ['01' => 5, '10' => 6];

$key = array_search(5, $array);
foo($key); // works

$key = array_search(6, $array);
foo($key); // crash

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions