1

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
)
3
  • 2
    Can't you just do $file_months = $nbr_mois? Commented Apr 10, 2014 at 11:43
  • +1 because I had to change my shorts after I read this! Commented Apr 10, 2014 at 11:46
  • 1
    You are comparing a value to an array. Use the array_search function. Commented Apr 10, 2014 at 11:46

5 Answers 5

3

i think array_merge will work for you without the loop.

Sign up to request clarification or add additional context in comments.

Comments

2

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);
   }
}

Comments

1

Or just replace

if($value!=$file_months)
    array_push($file_months,$value);

with

if($value!=$file_months[$key])
    $file_months[$key] = $value;

1 Comment

Good point. The OP didn't say if he wanted to append only nonexistant values, or he wanted them overwritten.
0

use in_array..

Instead of

if($value!=$file_months) {

}

Use this..

if(!in_array($value,$file_months)) {

}

Comments

0

Use in_array() method as shown below:

if(!in_array($value, $file_months))

instead of

if($value!=$file_months)

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.