Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push data into array with for loop

I need to generate an array like this:

$person = array(
    array(
        "name" => "brian",
        "age" => "25"
    ),
    array(
         "name" => "simon",
         "age" => "21"
    )
);

I put this code into a simple for loop:

for ($x = 0; $x <= 10; $x++) {
    $new_array = array("name"=>'Brian', "age"=>'25');
    array_push($person, $new_array);
} 

If the for loop must be repeated 10 times I should have 10 rows with Brian name and age 25 but I have this result:

Array ( [1] => Array ( [name] => Brian [age] => 25 ) [value] => Array ( [name] => Brian [age] => 25 ) [0] => 0 [key] => 0 ) 

Am I doing something wrong with the array_push? Thanks

like image 833
simo93bs Avatar asked Jan 03 '23 17:01

simo93bs


1 Answers

Create $new_array = array();

for ($x = 0; $x <= 10; $x++) {
    $new_array[] = array("name"=>'Brian', "age"=>'25');   
}
print_r($new_array);

Out put will be

Array ( [0] => Array ( [name] => Brian [age] => 25 ) 
    [1] => Array ( [name] => Brian [age] => 25 ) 
    [2] => Array ( [name] => Brian [age] => 25 ) 
    [3] => Array ( [name] => Brian [age] => 25 ) 
    [4] => Array ( [name] => Brian [age] => 25 ) 
    [5] => Array ( [name] => Brian [age] => 25 ) 
    [6] => Array ( [name] => Brian [age] => 25 ) 
    [7] => Array ( [name] => Brian [age] => 25 ) 
    [8] => Array ( [name] => Brian [age] => 25 ) 
    [9] => Array ( [name] => Brian [age] => 25 ) 
    [10] => Array ( [name] => Brian [age] => 25 ) 
)
like image 95
Suneel Kumar Avatar answered Jan 11 '23 09:01

Suneel Kumar