tags:

views:

884

answers:

4

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.

+7  A: 

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

Greg
Wow. I read the list of array functions and totally missed that one. Thanks.
Thomas Owens
A: 

I don't have the book next to me at the moment, but doesn't php have an option when building the array to disregard the value if it is already in the array, thus building the array unique to begin with?

Keng
But I'm not building the array. I'm merging multiple arrays and then removing duplicate values. But there are methods to find if the key or value is already in the array.
Thomas Owens
oh, didn't realize you were merging.
Keng
A: 

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);
}
Zak
A: 

In the few cases I've tried using for instead of foreach, I soon regretted it.

It can really always be avoided, you can even use foreach but ignore the values and use the key, almost forgetting that its a foreach instead of for, but avoiding any gaps in your keys and automatically have your bounds taken care of without length/min/max functions or anything.

ex.

foreach($myArray as $key=>$val)
{
myArray[$key] = myFunction(myArray[$key]);
}

I've particularly found this useful with parallel arrays.

$a = getA(); $b = getB();
foreach($a as $key=>val)
{
$sql = "INSERT INTO table (field1, field2) VALUES ($a[$key], $b[$key])";
}

sorry for formatting, im new here and need to look into this more.

jon_darkstar