1

In my application I am using array_diff function as -

$aDeleteCountryCodes = array_diff($aCurrentCountryCodes, $aNewCountryCodes);

Now what happens is, the resultant array, $aDeleteCountryCodes, some times comes as

Array
(
[2] => 213
)

and some times

Array
(
[2] => 213
[3] => 355
)

which messes my for loop that I use to delete records from database. For loop is like this-

for ($i=0; $i <= count($aDeleteCountryCodes); $++)
{
   // Delete record $aDeleteCountryCodes[$i]
}

what I want is the array to come as -

Array
(
[0] => 213
)

Array
(
[0] => 213
[1] => 355
)

so that the looping becomes easier. I hope I made it clear. How can I do this ?

4 Answers 4

3
  1. Use array_values.
  2. Use foreach instead of "manual for loops."
2

Rather than reset the keys, it's preferable to just iterate over the existing keys:

   foreach ($aDeleteCountryCodes as $key => $value) {
     // delete goes here.
   }
2

Use array_values(array_diff($aCurrentCountryCodes, $aNewCountryCodes));

1

You can just get the values out into a new array:

$aDeleteCountryCodes = array_values($aDeleteCountryCodes) //Keys resetted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.