Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove values from an array whilst renumbering numeric keys

I have an array which may contain numeric or associative keys, or both:

$x = array('a', 'b', 'c', 'foo' => 'bar', 'd', 'e');
print_r($x);
/*(
    [0] => a
    [1] => b
    [2] => c
    [foo] => bar
    [3] => d
    [4] => e
)*/

I want to be able to remove an item from the array, renumbering the non-associative keys to keep them sequential:

$x = remove($x, "c");
print_r($x);
/* desired output:
(
    [0] => a
    [1] => b
    [foo] => bar
    [2] => d
    [3] => e
)*/

Finding the right element to remove is no issue, it's the keys that are the problem. unset doesn't renumber the keys, and array_splice works on an offset, rather than a key (ie: take $x from the first example, array_splice($x, 3, 1) would remove the "bar" element rather than the "d" element).

like image 938
nickf Avatar asked Jan 04 '10 02:01

nickf


2 Answers

This should re-index the array while preserving string keys:

$x = array_merge($x);
like image 79
Kevin Avatar answered Sep 28 '22 09:09

Kevin


You can fixet with next ELEGANT solution:

For example:

<?php

$array = array (
    1 => 'A',
    2 => 'B',
    3 => 'C'
);

unset($array[2]);

/* $array is now:
Array (
    1 => 'A',
    3 => 'C'
);
As you can see, the index '2' is missing from the array. 
*/

// SOLUTION:
$array = array_values($array);

/* $array is now:
Array (
    0 => 'A',
    1 => 'C'
);
As you can see, the index begins from zero. 
*/
?>
like image 32
Bezerik Avatar answered Sep 28 '22 08:09

Bezerik