Your PHP array indices getting messed up when unsetting values?

Thats because in PHP arrays are internally handled like hashes.
Let me give you an example:

<?php  
// Lets assumme we have an array of numbers
$numbers = array(1, 2, 3, 4, 5);

// Which we are going to inspect
var_dump($numbers);

// Output is
/*
array(4) {  
    [0] => int(1)
    [1] => int(2)
    [2] => int(3)
    [3] => int(4)
    [4] => int(5)
}
*/

// And we are going to unset the 3rd element
unset($numbers[2]);

// Lets inspect again
var_dump($numbers);

// Output is
/*
array(4) {  
    [0] => int(1)
    [1] => int(2)
    [3] => int(4)
    [4] => int(5)
}
*/
?>

As you can see all other indices dont get touched, we now have four elements and the last index (or better key) is still 4.

So far so good, but how do we fix this. Well, there are two options. You can re-index the array after unsetting a value using array_values or, even better, use array_splice to delete a value off an array (yes, this is similar to the splice function in Javascript).

Let me show you the first option using array_values and the example from above:

<?php  
// Again, an array of 5 numbers
$numbers = array(1, 2, 3, 4, 5);

// Unsetting the 3rd element
unset($numbers[2]);

// And re-indexing the array
$numbers = array_values($numbers);

// Inspecting the array
var_dump($numbers);

// And there you go
/*
array(4) {  
    [0] => int(1)
    [1] => int(2)
    [2] => int(4)
    [3] => int(5)
}
*/
?>

Great, 3rd index got unset, last index is now 3. Second option, using array_splice only takes one line to delete the element:

<?php  
// 5 numbers
$numbers = array(1, 2, 3, 4, 5);

// Unsetting 1 element at index 2 (3rd element of course)
array_splice($numbers, 2, 1);

// Inspecting the array again
var_dump($numbers);

// Yay
/*
array(4) {  
    [0] => int(1)
    [1] => int(2)
    [2] => int(4)
    [3] => int(5)
}
*/
?>

Good, we deleted the third element, last index is 3, good job :-)

comments powered by Disqus