4

I have a array

Array (
    [1] => Vice President
    [3] => Secretary
    [5] => Treasurer
) 

I want make it change to

Array (
    [0] => Vice President
    [1] => Secretary
    [2] => Treasurer
) 

I have try us php for loop function

$ub_new_arr_sort = array();
for ($i3 = 0; $i3 < count($ub_new_arr); $i3++) {
    $ub_new_arr_sort[] = $ub_new_arr[$i3];
}

but seem like not work at all, any idea?

1
  • For the record, "your" way did not work because you're iterating over the fictional indexes 0..2. However, the array used the indexes 1, 3, and 5. The foreach construct would have worked, although @Francois Deschenes' answer is more elegant, IMO. Commented Jul 1, 2011 at 5:55

2 Answers 2

12

Just use array_values.

$array = array_values($array);
Sign up to request clarification or add additional context in comments.

1 Comment

If you found this was the best solution be sure to mark it as the answer!
1

Use foreach instead of for to be 'key independant':

foreach($oldarray as $position){
    $newArray[] = $position;
}
print_r($newArray);

1 Comment

@wyman Just so that you understood what was wrong in your code: your for was looping from 0 to count(), so the values were 0,1,2 while keys actually are 1,3,5. In fact PHP was generating E_NOTICEs when you tried to read non-existent keys 0 and 2. Always keep error_reporting=E_ALL|E_STRICT in php.ini on your development machine, it will prevent you from making obvious bugs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.