Rebase array keys after unsetting elements

TuK

I have an array:

$array = array(1,2,3,4,5);

If I were to dump the contents of the array they would look like this:

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

When I loop through and unset certain keys, the index gets all jacked up.

foreach($array as $i => $info)
{
  if($info == 1 || $info == 2)
  {
    unset($array[$i]);
  }
}

Subsequently, if I did another dump now it would look like:

array(3) {
  [2] => int(3)
  [3] => int(4)
  [4] => int(5)
}

Is there a proper way to reset the array so it's elements are Zero based again ??

array(3) {
  [0] => int(3)
  [1] => int(4)
  [2] => int(5)
}
Naftali aka Neal

Try this:

$array = array_values($array);

Using array_values()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related