ltvie ltvie - 5 months ago 11
PHP Question

Add item in array with key?

I have some PHP code and I was tried many times but no luck. this is my case
i have one array that declare in difference place and want to merge in looping

$data[] = ['sales' => 'mark'];

for($i=0;$i<3;$i++){
data[$i]="some value".$i;
}


the result

Array ( [0] => Array ( [sales] => mark ) [0] => some value0 [1] => some value1 [2] => some value2 )


my expected

Array ( [0] => Array ( [sales] => mark [0] => some value0 [1] => some value1 [2] => some value2 ) )

Answer

I think you are looking for:

$data['sales'] = 'mark';

for($i=0;$i<3;$i++){
 $data[$i]="some value".$i;
}
$x[0] = $data;
print_r($x);

print_r($data);

That outputs this:

Array
(
    [0] => Array
        (
            [sales] => mark
            [0] => some value0
            [1] => some value1
            [2] => some value2
        )
)
Comments