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."
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

2

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

Comments

1

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

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

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.