You can not unset a numeric key of an array, if key is a string. See this example:
// Create a simple array with 3 different key types
$test[1] = array(
10 => array('apples'),
"20" => array('bananas'),
'30' => array('peaches')
);
$test[2] = (array) json_decode(json_encode($test[1]));
$test[3] = (array) (object) $test[1];
// array form a stdClass object
$testClass = new stdClass();
$testClass->{10} = array('apples');
$testClass->{"20"} = array('bananas');
$test[4] = (array) $testClass[6];
echo "
";
foreach($test as $testNum => $arr) {
echo "\nTest: " . $testNum . " \n";
var_dump($arr);
foreach($arr as $key => $fruit) {
echo "key: " . $key . "\n";
echo "key exists: ";
var_dump(array_key_exists(strval($key), $arr));
echo "typeof key is: " . gettype($key) . "\n";
unset($arr[$key]);
}
var_dump($arr);
echo "\n" . str_repeat("-", 80);
}
echo "
";And here is the output:
Test: 1
array(3) {
[10]=>
array(1) {
[0]=>
string(6) "apples"
}
[20]=>
array(1) {
[0]=>
string(7) "bananas"
}
[30]=>
array(1) {
[0]=>
string(7) "peaches"
}
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}
--------------------------------------------------------------
Test: 2
array(3) {
["10"]=>
array(1) {
[0]=>
string(6) "apples"
}
["20"]=>
array(1) {
[0]=>
string(7) "bananas"
}
["30"]=>
array(1) {
[0]=>
string(7) "peaches"
}
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
key: 30
key exists: bool(false)
typeof key is: string
array(3) {
["10"]=>
array(1) {
[0]=>
string(6) "apples"
}
["20"]=>
array(1) {
[0]=>
string(7) "bananas"
}
["30"]=>
array(1) {
[0]=>
string(7) "peaches"
}
}
--------------------------------------------------------------
Test: 3
array(3) {
[10]=>
array(1) {
[0]=>
string(6) "apples"
}
[20]=>
array(1) {
[0]=>
string(7) "bananas"
}
[30]=>
array(1) {
[0]=>
string(7) "peaches"
}
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}
--------------------------------------------------------------
Test: 4
array(2) {
["10"]=>
array(1) {
[0]=>
string(6) "apples"
}
["20"]=>
array(1) {
[0]=>
string(7) "bananas"
}
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
array(2) {
["10"]=>
array(1) {
[0]=>
string(6) "apples"
}
["20"]=>
array(1) {
[0]=>
string(7) "bananas"
}
}
--------------------------------------------------------------
Fix the problem with a rebuild of the array:
$oldArray = $array();
$array = array();
foreach($oldArray as $key => $item) {
$array[intval($key)] = $item;
}