Remove duplicates from an array, then remove nulls, then restructure

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

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.

Tags:

Php

Arrays