Search code examples
phparraysarray-push

Add elements to a dynamic array with array_push


I have this array file_months that changes when an new month it adds to a folder:

Array
(
    [0] => 01
    [1] => 02
    [2] => 03
)

What I want is to display all the months in a select option, so I tried this :

$nbr_mois = array('0'=>'01','1'=>'02','2'=>'03','3'=>'04','4'=>'05','5'=>'06','6'=>'07','7'=>'08','8'=>'09','9'=>'10','10'=>'11','11'=>'12');
foreach ($nbr_mois as $key => $value) {
    if($value!=$file_months)
array_push($file_months,$value);
}

but it doesn't add a missing months, it adds them all! Like this :

Array
(
    [0] => 01
    [1] => 02
    [2] => 03
    [3] => 01
    [4] => 02
    [5] => 03
    [6] => 04
    [7] => 05
    [8] => 06
    [9] => 07
    [10] => 08
    [11] => 09
    [12] => 10
    [13] => 11
    [14] => 12
)

Solution

  • i think array_merge will work for you without the loop.