How to remove values ​​from an array when renumbering numeric keys

I have an array that can 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 element from an array, renumber non-associative keys to save them in sequence:

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

Finding the right item to delete is not a problem; these are the keys that are the problem. unset does not renumber the keys, and array_splice works with an offset rather than a key (i.e., take $ x from the first example, array_splice($x, 3, 1) will remove the bar element, not the d element) .

+6
arrays php associative-array
source share
5 answers

This should reindex the array while storing the string keys:

 $x = array_merge($x); 
+13
source share

You can fix the following 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. 
 * /
 ?>
+2
source share

I came up with this, although I'm not sure if this is better:

 // given: $arr is the array // $item is the item to remove $key = array_search($item, $arr); // the key we need to remove $arrKeys = array_keys($arr); $keyPos = array_search($key, $arrKeys); // the offset of the item in the array unset($arr[$key]); array_splice($arrKeys, $keyPos, 1); for ($i = $keyPos; $i < count($arrKeys); ++$i) { if (is_int($arrKeys[$i])) --$arrKeys[$i]; // shift numeric keys back one } $arr = array_combine($arrKeys, $arr); // recombine the keys and values. 

Here are a few things I forgot, for the sake of brevity. For example, you should check if the array is associative, and also if the key you are deleting is a string or not before using the above code.

0
source share

Try array_diff (), it cannot properly order the new array if the following should not work:

You will need to iterate over it into the delete function.

 function remove($x,$r){ $c = 0; $a = array(); foreach ($x as $k=>$v){ if ($v != $r) { if (is_int($k)) { $a[$c] = $v; $c++; } else { $a[$k] = $v; } } } return $a; } 

DC

0
source share

I don’t think there is an elegant solution to this problem, you probably need to loop around the array and reorder the keys yourself.

0
source share

All Articles