Home > Enterprise >  String to array when two comma to one array with php
String to array when two comma to one array with php

Time:12-21

my string has

$string = "apple,banana,orange,lemon";

I want to as

$array = [
           [apple,banana],
           [orange,lemon]
]

CodePudding user response:

Use array_chunk in combination with explode defined in php https://www.php.net/manual/en/function.array-chunk.php

<?php

    $string = "apple,banana,orange,lemon";
   
    $input_array = explode (",", $string);
   
    print_r(array_chunk($input_array, 2));
?> 

Will output as below:

Array
(
    [0] => Array
        (
            [0] => apple
            [1] => banana
        )

    [1] => Array
        (
            [0] => orange
            [1] => lemon
        )

)

CodePudding user response:

I hope this helps you get on your way. To transform a string to an array, you can use

$elements = explode(',', $string);

This will leave you with this array: ($elements == [apple,banana,orange,apple])

From there, you can build it the way you want, like:

$array[] = [$elements[0], $elements[1]];
$array[] = [$elements[2], $elements[3]];

This results in the array you are looking for, but this solution is only for the string you've given with four elements, separated by comma.

  •  Tags:  
  • php
  • Related