0

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?

1

4 Answers 4

2

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';
Sign up to request clarification or add additional context in comments.

Comments

1

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']
];

Comments

1

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';

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.