Convert string to array after count five comma in the string using PHP

Issue

I have a string is below,

$string = "div-item-0,4,maintype:menu| heading: Quick Link|  isactive:1,0,0, div-item-1,4,maintype:text| heading:Image|  isactive:1,4,0, div-item-2,4,maintype:social| heading:Social|  isactive:1,8,0";"

Now I would like to convert this string as a sub-string to be an array element is as below,

$array = [
    "div-item-0,4,maintype:menu| heading: Quick, Link| isactive:1,0,0",
    "div-item-1,4,maintype:text| heading:Image| isactive:1,4,0",
    "div-item-2,4,maintype:social| heading:Social| isactive:1,8,0",
];

After five commas counted in the $string, a substring will be converted as an array element.
How can I do it using PHP?

Solution

You could use the array_chunk method to solve this

<?php

$string = "
div-item-0,4,maintype:menu| heading: Quick Link|  isactive:1,0,0,  
div-item-1,4,maintype:text| heading:Image|  isactive:1,4,0,  
div-item-2,4,maintype:social| heading:Social|  isactive:1,8,0";


$temp = explode(',', $string); // just create one big array
$temp = array_chunk($temp, 5); // group the array per 5 parts
foreach($temp as &$value) $value = trim(implode(',', $value)); // recombine to one string

var_dump($temp);

demo

Answered By – DarkBee

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published