Resetting array keys after unsettling a few of them

I have felt this need quite a few times in the past as well.

I have an array:

$cart = array(
  0=>'first item',
  1=>'second item',
  2=>'third item'
);

After doing unset($cart[1]) new array i am left with is:

$cart = array(
  0=>'first item',
  2=>'third item'
);

but i want to look it like:

$cart = array(
  0=>'first item',
  1=>'third item'
);

In the past i had been doing this by hooks or crooks. Today i felt a need to do it once again and this time i had decided to bring up with a permanent solution to it. The solution which i finally came with is a much simpler than expected. Here is it:

$cart = array_values($cart);

Isn’t it very useful? :)

One thought on “Resetting array keys after unsettling a few of them

Leave a Reply

Your email address will not be published. Required fields are marked *