0

Hi I have an array, I need to change the keys, in an orderly manner but don't change the order the values are. e.g.

$a = array (
 0=>'h',
 1=>'blabla',
 2=>'yes'
);

I used

unset($a[1]);

but i need the key to restart calculating the keys 0,1,2 ... etccc so i don't end up with:

array(
 0 => 'h',
 2 => 'yes'
)

but it should come return:

array(
 0 => 'h',
 1 => 'yes'
)

3 Answers 3

5

You need to apply array_values on your array to re-index.

$a = array_values($a);

Bonus: If you also need to order your values you can use sort and it too will re-index your array.

Note: By using any of array_values or sort you will loose any string keys you may have.

Sign up to request clarification or add additional context in comments.

Comments

3

Call array_values on it:

$a = array (
 0=>'h',
 1=>'blabla',
 2=>'yes'
);

unset($a[1]);

$a = array_values($a);

var_dump($a); 
/*
array(2) {
  [0]=>
  string(1) "h"
  [1]=>
  string(3) "yes"
}
*/

Comments

2

You can also use array_splice() instead of unset(), which will automatically reindex the array elements:

$a = array (
 0=>'h',
 1=>'blabla',
 2=>'yes'
);

array_splice($a,1,1);

var_dump($a);

4 Comments

But that's a bit of an overkill. There are some other functions that will do that. array_merge for example (for his case).
Is it really overkill compared with executing an array_values() immediately after an unset()?
Assuming he wants to eliminate exactly one element I guess it may be a bit faster with array_splice, but I have no serious evidence. Also PHP is not exactly a language where speed should be the priority :). I'll give you a +1 for your combo solution to unset and re-index.
It might be interesting to see which was the faster method, but it would take a much larger array than the OP is using to see any difference in speed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.