Search code examples
phparraysassociative-arrayexplodedelimited

Split string with only one delimiting character into key-value pairs


I have a colon-delimited string like this:

"Part1:Part2:Part3:Part4"

With explode I can split the string into an array:

echo '<pre>';
print_r(explode(":", "Part1:Part2:Part3:Part4"));
echo '</pre>';

Output:

Array
(
    [0] => Part1
    [1] => Part2
    [2] => Part3
    [3] => Part4
)

But I need associative array elements like this:

Array
    (
        [Part1] => Part2
        [Part3] => Part4
    )

UPDATE

echo '<pre>';
list($key, $val) = explode(':', 'Part1:Part2:Part3:Part4');
$arr= array($key => $val);
print_r($arr);
echo '</pre>';

Result:

Array
(
    [Part1] => Part2
)

Solution

  • Try this

    $string = "Part1:Part2:Part3:Part4";
    $arr = explode(":", $string);
    
    $key = "";
    $i = 0;
    $newArray = [];
    foreach($arr as $row){
        if($i == 0){
            $key = $row;
            $i++;
        } else {
            $newArray[$key] = $row;
            $i = 0;
        }
    }
    
    echo "<pre>";
    print_r($newArray);
    echo "</pre>";