What is the best way to prevent duplicate key on type?
Example:
//Credits @bwoebi
$obj = (object)array(1,2,3);
$obj->{1} = "Duplicate key 1";
$obj->{2} = "Duplicate key 2";
$obj->{3} = "Duplicate key 3";
$array = (array)$obj ;
print_r($array);
Output
Array
(
[0] => 1
[1] => 2
[2] => 3
[1] => Duplicate key 1
[2] => Duplicate key 2
[3] => Duplicate key 3
)
Now I know that some smart people will say it, because one keyis string, and the other intusesvar_dump
var_dump($array);
Output
array (size=6)
0 => int 1
1 => int 2
2 => int 3
'1' => string 'Duplicate key 1' (length=15)
'2' => string 'Duplicate key 2' (length=15)
'3' => string 'Duplicate key 3' (length=15)
But the main problem is that it’s not even possible to get the key
echo $array['1'] ,PHP_EOL;
echo $array[1] ,PHP_EOL;
Output
2
2
Is there any workaround for this problem without having to quote? Obviously, I would never have made this mistake if @PeeHaa didn’t give a beer again, but I think any answer should help educated developers PHP.
Note . - This can be easily resolved using array_values, sortor any php function that changes the position of the key
Example
sort($array);
print_r($array);
Output
Array
(
[0] => Duplicate key 1
[1] => Duplicate key 2
[2] => Duplicate key 3
[3] => 1
[4] => 2
[5] => 3
)
source
share