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.
views:
884answers:
4I 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?
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);
}
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.