6

I have an array (sizeofarray = 5)

$city[0] = 'Newyork'
$city[1] = 'Paris'
$city[2] = 'Paris'
$city[3] = 'Newyork'
$city[4] = 'Amsterdam'
(sizeofarray = 5)

I used array_unique() to remove dupes and got this:

$city[0] = 'Newyork'
$city[1] = 'Paris'
$city[4] = 'Amsterdam'
(sizeofarray = 3)

But now I want this:

$city[0] = 'Newyork'
$city[1] = 'Paris'
$city[2] = 'Amsterdam'
(sizeofarray = 3)

Is there some function to achieve this?

2
  • 2
    I'm not sure why you would be getting empty for 2 and 3. array_unique completely removes the duplicate items from the array, so you should be getting the result you're showing in the last snippet. See: pastie.org/5114229 Commented Oct 25, 2012 at 12:15
  • Ok I am sorry.. I am running a loop where $city[2] shows error. Reframing my question Commented Oct 25, 2012 at 12:19

3 Answers 3

10

Use array_filter after you run the array through array_unique:

$city = array_filter($city);

From the documentation:

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

You may run into an error, however, if one of your array elements is equal to "0", as when converted to boolean, its value is false. In that case, you'll have to use a custom callback function.


In your question, it appears that only the array indexing is out of order, and there are not actual empty string elements in your array. Try running the array though array_values after array_unique to reset the indexing:

$city = array_unique($city); 
$city = array_values($city); 
Sign up to request clarification or add additional context in comments.

1 Comment

I am reframing my question. I am running a loop afterwards where $city[2] shows null. It obviously will, because the key itself is absent.
2

In addition to Tim Cooper's reply, use array_values() to reindex the array:

$city = array_unique($city);
$city = array_filter($city);
$city = array_values($city);

And make sure same cities have same names, because 'New York' != 'Newyork'. Otherwise you'll need additional filtering.

Comments

0

Try like this :

$city=array_values(array_unique($city));

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.