Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode a string to associative array without using loops? [duplicate]

Tags:

arrays

php

I have a string like 1-350,9-390.99,..., and I need to turn it into an associative array like this:

 Array
    (
        [1] => 350
        [9] => 390.99
        ...........
    )

Is it possible to do this using only array functions, without a loop?

like image 411
Pramod Avatar asked Jan 03 '13 05:01

Pramod


5 Answers

PHP 5.5+ two-line solution, using array_chunk and array_column:

$input  = '1-350,9-390.99';

$chunks = array_chunk(preg_split('/[-,]/', $input), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));

print_r($result);

Yields:

Array
(
    [1] => 350
    [9] => 390.99
)

See it online at 3v4l.org.

like image 60
bishop Avatar answered Nov 03 '22 13:11

bishop


Here's a way to do it without a for loop, using array_walk:

$array = explode(',', $string);
$new_array = array();
array_walk($array,'walk', $new_array);

function walk($val, $key, &$new_array){
    $nums = explode('-',$val);
    $new_array[$nums[0]] = $nums[1];
}

Example on Ideone.com.

like image 43
bozdoz Avatar answered Nov 03 '22 14:11

bozdoz


Something like this should work:

$string = '1-350,9-390.99';

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

foreach ($a as $result) {
    $b = explode('-', $result);
    $array[$b[0]] = $b[1];
}
like image 8
jel Avatar answered Nov 03 '22 12:11

jel


This uses array_walk with a closure.

<?php
$string = "1-350,9-390.99";
$partial = explode(',', $string);
$final = array();
array_walk($partial, function($val,$key) use(&$final){
    list($key, $value) = explode('-', $val);
    $final[$key] = $value;
});
print_r($final);
?>

Interactive fiddle.

like image 7
hafichuk Avatar answered Nov 03 '22 12:11

hafichuk


$string = '1-350,9-390.99........';
$final_result = array();
foreach (explode(',', $string) as $piece) {
    $result = array();
    $result[] = explode('-', $piece);
    $final_result[$result[0]] = $result[1];
}

print_r($final_result);
like image 3
Vinoth Babu Avatar answered Nov 03 '22 12:11

Vinoth Babu