16

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.

3 Answers 3

42

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

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

1 Comment

Wow. I read the list of array functions and totally missed that one. Thanks.
1

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);
}

Comments

0

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])";
}

Comments

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.