I get stuck with a strange PHP behaviour after a cast. Here is the code :
$obj = new stdClass();
$obj->{'0'} = "test";
$array = (array)$obj;
var_dump($array);
This code will output :
array(1) { ["0"]=> string(4) "test" }
Absolutely normal.
Now I add some code :
foreach ($array as $key => $value) {
$array[$key] = strtoupper($value);
}
var_dump($array);
This code outputs :
array(2) {
["0"]=>
string(4) "test"
[0]=>
string(4) "TEST"
}
Why my $key casted to int ?
If I try a simpler example :
$array = array("0" => "test");
foreach ($array as $key => $value) {
$array[$key] = strtoupper($value);
}
var_dump($array);
This will output :
array(1) { [0]=> string(4) "TEST" }
Does somebody know why there is a cast of my $key to int ?
Update
I tried to force to cast my key to string :
$array["{$key}"] = $value;
and
$array[(string)$key] = $value;
But they are inserted as int. So my question should be : is there a way to insert keys as string into an array?
I know that I can solve my problem by using a second array and dismiss strings :
$obj = new stdClass();
$obj->{'0'} = "test";
$array = (array)$obj;
$array2 = array();
foreach ($array as $key => $value) {
$array2[$key] = strtoupper($value);
}
But it would be nice to make it in a more beautiful way, conserving data type (and avoiding duplicating entries while iterating them as previously demonstrated).