Search code examples
phparraysstringsubstring

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


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