0

Suppose I have a comma separated string like as follows:

1,Sunday,2,Monday,3,Tuesday,4,Wednesday,5,Thursday,6,Friday,7,Saturday

How can I make it an pairwise array in PHP like as follows --

array
(
  [1] => Sunday,
  [2] => Monday,
  [3] => Tuesday,
  [4] => Wednesday,
  [5] => Thursday,
  [6] => Friday,
  [7] => Saturday,
);
3
  • Have you tried something? Commented May 4, 2015 at 11:43
  • 2
    Do you really need the commas in your array? Commented May 4, 2015 at 11:46
  • No I am not trying anything.But now I will try best of these suggestions. Commented May 4, 2015 at 16:13

3 Answers 3

2

Simple answer (requires PHP >= 5.5.0): if you don't need the trailing comma at the end of each value

$string = '1,Sunday,2,Monday,3,Tuesday,4,Wednesday,5,Thursday,6,Friday,7,Saturday';

$data = array_chunk(
    explode(',', $string),
    2
);
$newArray = array_combine(
    array_column($data, 0),
    array_column($data, 1)
);
var_dump($newArray);

If you do need the trailing comma, you can add:

array_walk(
    $newArray,
    function(&$value) {
        $value .= ',';
    }
);
Sign up to request clarification or add additional context in comments.

1 Comment

I like your solution, especially because it doesn't require a loop! <3
1

If you have such static data like weekdays and weekday numbers, it certainly would be the easiest to just use a static array:

$weekdays = array(
    1 => 'Sunday',
    2 => 'Monday',
    3 => 'Tuesday',
    4 => 'Wednesday',
    5 => 'Thursday',
    6 => 'Friday',
    7 => 'Saturday',
);

If you have to parse your comma separated string, you can use this:

$string = '1,Sunday,2,Monday,3,Tuesday,4,Wednesday,5,Thursday,6,Friday,7,Saturday';
$parts = explode(',', $string);
$weekdays = array();

for ($i = 0; $i < count($parts); ) {
    $weekdays[$parts[$i]] = $parts[++$i];
    ++$i;
}

print_r($weekdays);

Output:

Array
(
    [1] => Sunday
    [2] => Monday
    [3] => Tuesday
    [4] => Wednesday
    [5] => Thursday
    [6] => Friday
    [7] => Saturday
)

It ain't pretty, but it does the job :).

1 Comment

Good suggestion to have a static array in the first place
0

This'll work for you.

$string = '1,Sunday,2,Monday,3,Tuesday,4,Wednesday,5,Thursday,6,Friday,7,Saturday.';
$dtd = explode(',', $string);
$array = array();
$i = 1;
foreach ($dtd as $key => $value){
    if($key % 2 == 1){
        $array[$i++] = $value;
    }
}

print_r($array);//Array ( [1] => Sunday [2] => Monday [3] => Tuesday [4] => Wednesday [5] => Thursday [6] => Friday [7] => Saturday. )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.