skip to Main Content

my string has

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

I want to as

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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
            )
    
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search