skip to Main Content

I have array $array["rlist"] that outputs:

Array (
    [0] => Array ( [0] => test1 )
    [1] => Array ( [0] => test2 )
    [2] => Array ( [0] => test3 )
    [3] => Array ( [0] => test4 )
    [4] => Array ( [0] => test5 ) 
)

When I try to edit like so:

$array["rlist"][0][0] = 'test1';
$array["rlist"][0][1] = 'test2';
$array["rlist"][0][2] = 'test3';
$array["rlist"][0][3] = 'test4';
$array["rlist"][0][4] = 'test5';

I get

Array ( 
    [0] => Array (
        [0] => test1
        [1] => test2 
        [2] => test3
        [3] => test4
        [4] => test5
    ) 
) 

What am I doing wrong?

4

Answers


  1. it’s expected because the element is in

    array[0][0]
    array[1][0]
    array[2][0]
    array[3][0]
    array[4][0]
    

    so if you want to edit then:

    $array["rlist"][0][0] = 'test1';
    $array["rlist"][1][0] = 'test2';
    $array["rlist"][2][0] = 'test3';
    $array["rlist"][3][0] = 'test4';
    $array["rlist"][4][0] = 'test5';
    
    Login or Signup to reply.
  2. If you format your original output, you would see the proper formatting you need…

    Array (
        [0] => Array ( [0] => test1 )
        [1] => Array ( [0] => test2 )
        [2] => Array ( [0] => test3 )
        [3] => Array ( [0] => test4 )
        [4] => Array ( [0] => test5 )
    )
    

    You can achieve this by setting each item seprately…

    $array = [];
    
    $array['rlist'][][] = 'test1';
    $array['rlist'][][] = 'test2';
    ...
    

    or set them in 1 chunk…

    $array = [];
    
    $array['rlist'] = [
        ['test1'],
        ['test2'],
        ['test3'],
        ['test4'],
        ['test5']
    ];
    
    Login or Signup to reply.
  3. You have an array like this:

    $array["rlist"] = 
        Array ( [0] => Array ( [0] => 'test1' ) ,
                [1] => Array ( [0] => 'test2' ) ,
                [2] => Array ( [0] => 'test3' ) ,
                [3] => Array ( [0] => 'test4' ) ,
                [4] => Array ( [0] => 'test5' ) 
        )
    

    The key is [$i++] and the value is an array, so you can edit like this :

    $array["rlist"][0][0] = 'test1';
    $array["rlist"][1][0] = 'test2';
    $array["rlist"][2][0] = 'test3';
    $array["rlist"][3][0] = 'test4';
    $array["rlist"][4][0] = 'test5';
    
    Login or Signup to reply.
  4. To avoid handwriting the 2d structure of single-element rows, you can hydrate a flat array with array_chunk() with 1 element per chunk.

    Code: (Demo)

    $tests = ['test1', 'test2', 'test3', 'test4', 'test5'];
    
    var_export(
        array_chunk($tests, 1)
    );
    

    Although it is not clear why you need to edit your array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search