Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP | Remove element from array with reordering?

How can I remove an element of an array, and reorder afterwards, without having an empty element in the array?

<?php
   $c = array( 0=>12,1=>32 );
   unset($c[0]); // will distort the array.
?>

Answer / Solution: array array_values ( array $input ).

<?php
   $c = array( 0=>12,1=>32 );
   unset($c[0]);
   print_r(array_values($c));
   // will print: the array cleared
?>
like image 904
19h Avatar asked Jan 31 '10 19:01

19h


2 Answers

array_values($c)

will return a new array with just the values, indexed linearly.

like image 99
Wim Avatar answered Oct 06 '22 04:10

Wim


If you are always removing the first element, then use array_shift() instead of unset().

Otherwise, you should be able to use something like $a = array_values($a).

like image 22
Matthew Avatar answered Oct 06 '22 06:10

Matthew