Abhijeet Kambli
Abhijeet Kambli

Reputation: 152

php string to associative array with value=>value pair

I have string

$string1 = `a,b,c,d`;

$array1 = explode(',', $string1);

Gives me :

array(
    (int) 0 => 'a',
    (int) 1 => 'b',
    (int) 2 => 'c'
    (int) 3 => 'd'
)

But I want it to be like this

array(
        'a' => 'a',
        'b' => 'b',
        'c' => 'c'
        'd' => 'd'
    )

How do I do that

Upvotes: 0

Views: 45

Answers (2)

whiteatom
whiteatom

Reputation: 1455

I think you have to create a new array after exploding...

$tmp_arr = explode(',', $string1);
$array1 = array();
foreach ($tmp_arr as $item){
    $array1[$item] = $item;
}

Upvotes: 1

sectus
sectus

Reputation: 15464

Use array_combine function

$string = `a,b,c,d`;
$array = explode(',', $string);    
var_dump(array_combine($array, $array));

Upvotes: 3

Related Questions