Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, how can I correct missing keys in an array?

Tags:

arrays

php

After using array_unique, an array without the duplicate values is removed. However, it appears that the keys are also removed, which leaves gaps in an array with numerical indexes (although is fine for an associative array). If I iterate using a for loop, I have to account for the missing indexes and just copy the keys to a new array, but that seems clumsy.

like image 960
Thomas Owens Avatar asked Oct 21 '08 15:10

Thomas Owens


2 Answers

$foo = array_values($foo); will re-number an array for you

like image 126
Greg Avatar answered Oct 14 '22 20:10

Greg


Instead of using for loops it sounds like you should use foreach loops. Apparently you don't care about indexes anyway since you are renumbering them.

This loop:

for ($i = 0; $i < $loopSize; $i++)
{
process($myArray[$i]);
}

turns into

foreach($myArray as $key=> $value)
{
    process($value);
    /** or process($myArray[$key]); */
}

or even more simply


foreach($myArray as $value)
{
    process($value);
}
like image 21
Zak Avatar answered Oct 14 '22 19:10

Zak