tnguyen444
tnguyen444

Reputation: 107

Parse an array of delimited values into a flat, associative array

I have an array that looks like this:

Array
(
    [0] => Dog:110
    [1] => Cat:111
    [2] => Mouse:101
)

Based on that array, I want to create another array to look like this

Array
(
   [Dog] => 110
   [Cat] => 111
   [Mouse] => 101
)

I know this is easy by creating my own function. But is there any way to do this with built in php function. Basically, I know I need to explode(), but is there any way to use this function in conjuction with one php's array functions or will I need to create my own function?

Upvotes: 2

Views: 89

Answers (3)

mickmackusa
mickmackusa

Reputation: 48031

A significant advantage of using sscanf() for this task is that you can explicitly dictate the data type of the numeric values at parsing time. Demo

$array = ['Dog:110', 'Cat:111', 'Mouse:101'];

$result = [];
foreach ($array as $v) {
    [$k, $result[$k]] = sscanf($v, '%[^:]:%d');
}
var_export($result);

Use %d for integers and %f for floating point values.

Output:

array (
  'Dog' => 110,
  'Cat' => 111,
  'Mouse' => 101,
)

Less attractively, you can wrap the leading word of each string in double quotes then implode the strings and wrap it all up in curly braces so that it can be parsed as valid JSON. This also provides the benefit of type casting the number values as integers. Demo

var_export(
    json_decode(
        '{' . implode(',', preg_replace('#^\w+#', '"$0"', $array)) . '}',
        true
    )
);

Beware that using certain dedicated parsers may have special behaviors. parse_str() will interpret url encoding. sscanf()'s placeholders need to be correctly implemented to avoid truncating values. json_encode() may fool with escaping or multibyte characters.

You can explode the values and assign elements using array destructuring syntax, but this means that the numeric values will be strings. Demo

$result = [];
foreach ($array as $v) {
    [$k, $result[$k]] = explode(':', $v, 2);
}
var_export($result);

You can manually cast each numeric value to an integer if desirable. Demo

$result = [];
foreach ($array as $v) {
    $temp = explode(':', $v, 2);
    $result[$temp[0]] = (int)$temp[1];
}
var_export($result);

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 79014

For fun one-liner:

parse_str(str_replace(':', '=', implode('&', $array)), $result);
print_r($result);

Upvotes: 1

Use explode

$new_arr=array();
foreach($yourarr as $v)
{
 $v = explode(':',$v);
 $new_arr[$v[0]]=$v[1];
}

Demo

Upvotes: 0

Related Questions