Reputation: 972
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
)
Upvotes: 1
Views: 1403
Reputation: 44581
Or just replace
if($value!=$file_months)
array_push($file_months,$value);
with
if($value!=$file_months[$key])
$file_months[$key] = $value;
Upvotes: 1
Reputation: 1
Use in_array() method as shown below:
if(!in_array($value, $file_months))
instead of
if($value!=$file_months)
Upvotes: 0
Reputation: 4858
use in_array
..
Instead of
if($value!=$file_months) {
}
Use this..
if(!in_array($value,$file_months)) {
}
Upvotes: 0
Reputation: 12246
Check if the key exists already
$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(!array_key_exists($key, $arrayname) {
if($value!=$file_months)
array_push($file_months,$value);
}
}
Upvotes: 2