0

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.

1
  • Are the inner values (e.g 9,12) arrays as well? If not this is just a single array with a string. Commented Jun 24, 2014 at 12:01

3 Answers 3

3
$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
)
*/
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

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.