Elavarasan
Elavarasan

Reputation: 2669

Isolate comma-separated values, remove duplicates and empty values, then sort

I want isolate individual values from a flat array of comma-separated values.

I also want to remove any empty strings and duplicated values then sort the result in an ascending fashion.

Sample input:

$cat_ids = [
    '9,12',
    '5,6,10,13,7,8,14',
    '13',
    '',
    '',
    '14',
    '15'
];

I have tried this so far,

$cat_ids = array_filter($cat_ids);

$cat_ids = array_map("unserialize", array_unique(array_map("serialize", $cat_ids)));
print_r($cat_ids);

My expected array should be like this,

['5,6,7,8,9,10,12,13,14,15']

OR

[
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '12',
    '13',
    '14',
    '15',
];

So it should be easily accessible of any element in this array.

Upvotes: 0

Views: 1060

Answers (3)

mickmackusa
mickmackusa

Reputation: 47904

Join the comma-delimited strings together with commas. Then split by one or more commas. Finally, sort from lowest to highest.

No iterated explosions, no array_filter, no merging.

Code: (Demo)

$result = array_unique(
    preg_split(
        '/,+/',
        implode(',', $array)
    )
);
sort($result);
var_export($result);

Upvotes: 0

Manohar singh
Manohar singh

Reputation: 509

Try this one hope this helps

 $a = Array
    (
         "9,12" , "5,6,10,13,7,8,14" , "13," , "" , "" , "14," , "15,"
    );


    echo '<pre>';
    print_r($a);

    $b = array_filter($a);

    print_r($b);


    $str = implode(',' , $b);
    echo $str;

    $exp = explode(',',$str);
    echo '<br>';
    print_r(array_filter($exp));

Upvotes: 1

Danijel
Danijel

Reputation: 12699

$array = array (
    0 => '9,12',
    1 => '5,6,10,13,7,8,14',
    2 => '13',
    3 => '',
    4 => '',
    5 => '14',
    6 => '15'
);

// turn strings into arrays with explode
$array = array_map( function( $item ) { return explode( ',', $item ); }, $array );
// merge all arrays
$array = call_user_func_array( 'array_merge', $array );
// remove empty and duplicate values    
$array = array_filter( array_unique( $array ) );
// sort 
sort( $array );

print_r( $array );
/* output: 
Array
(
    [0] => 5
    [1] => 6
    [2] => 7
    [3] => 8
    [4] => 9
    [5] => 10
    [6] => 12
    [7] => 13
    [8] => 14
    [9] => 15
)
*/

Upvotes: 3

Related Questions