2

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
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Trombone0904
  • 4,132
  • 8
  • 51
  • 104

3 Answers3

0

Alternative solution using only array_* functions.

  • Collect all values that are going to be keys for the resultant array.
  • Collect all values that are going to be actual values for the resultant array.
  • Combine both using array_combine().

Snippet:

<?php

$str = "Part1:Part2:Part3:Part4";

$res = array_combine(
        array_map(fn($v) => $v[0], array_chunk(explode(':',$str),2)),
        array_map(fn($v) => $v[1], array_chunk(explode(':',$str),2))
);
nice_dev
  • 17,053
  • 2
  • 21
  • 35
0

Using a for loop, you could also use the modulo operator % and create the key in the if part.

The if clause will be true for the first item having the key first and then the value in the else part, toggeling the keys and the values.

$str = "Part1:Part2:Part3:Part4";
$parts = explode(':', $str);
$result = [];

for ($i = 0; $i < count($parts); $i++) {
    $i % 2 === 0 ? $k = $parts[$i] : $result[$k] = $parts[$i];
}    
print_r($result);

Output

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

See a php demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
-1

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>";
Rully
  • 24
  • 3