Kuubs
Kuubs

Reputation: 1340

Put string into key value array

Hi I got the following string:

info:infotext,
dimensions:dimensionstext

and i need to put these values into an array in PHP. What is the regex function to put these into an array. I studied the regex codes but it's kinds confusing to me.

I want to put the info as the key and he infotext as the value into an array like this:

Array {

[info] => infotext
[dimensions] => dimensionstext

}

Upvotes: 0

Views: 42

Answers (2)

LF-DevJourney
LF-DevJourney

Reputation: 28529

Demo here

<?php
$string ='info:infotext,
dimensions:dimensionstext';
$array = array_map(function($v){return explode(':', trim($v));}, explode(',', $string));   
foreach($array as $v)
{
  $o[$v[0]] = $v[1];
}
print_r($o);

Upvotes: 1

Nishant Nair
Nishant Nair

Reputation: 2007

You can use array_chunk and array_combine

    <?php
    $input  = 'info:infotext,
    dimensions:dimensionstext';

    $chunks = array_chunk(preg_split('/(:|,)/', $input), 2);
    $result = array_combine(array_column($chunks, 0), array_column($chunks, 1));

    print_r($result);   

http://ideone.com/dRtref

Upvotes: 1

Related Questions