Search code examples
phparraysassociative-arrayexplodearray-combine

Comma-separated string to associative array with lowercase keys


I have a string like this:

$string = 'Apple, Orange, Lemone';

I want to make this string to:

$array = array('apple'=>'Apple', 'orang'=>'Orange', 'lemone'=>'Lemone');

How to achieve this?

I used the explode function like this:

$string = explode(',', $string );

But that only gives me this:

Array ( [0] => Apple [1] => Orange [2] => Lemone )

Somebody says this question is a duplicate of this SO question: Split a comma-delimited string into an array?

But that question is not addressing my problem. I have already reached the answer of that question, please read my question. I need to change that result array's key value and case. see:

Array
(
    [0] => 9
    [1] => [email protected]
    [2] => 8
)

to like this

Array
(
    [9] => 9
    [[email protected]] => [email protected]
    [8] => 8
)

Solution

  • You may try :

    $string = 'Apple, Orange, Lemone';
    $string = str_replace(' ', '', $string);
    
    $explode = explode(',',$string);
    
    $res = array_combine($explode,$explode);
    
    echo '<pre>';
    print_r($res);
    echo '</pre>';
    

    Or if you need to make lower case key for resulting array use following :

    echo '<pre>';
    print_r(array_change_key_case($res,CASE_LOWER));
    echo '</pre>';