0

I am trying to create a calendar in php. As a first step, I am just willing to make a function that echo my variable but it is not working so far.

Yet, everything works just fine outside of the function.

I have tried to declare $month first so it is not empty. I also tried to put the use keyword in my function but it doesn't work, same with declaring $months as a global.

I really can't get it to work and I thank you in advance for your help.

Here is my .php code :

<?php

$months = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
echo $months[0];

$month = 1;
echo $month;
echo $month - 1;
echo $months[$month - 1];

function afficherMois($month){
    if ($month < 1 || $month > 12){
        echo "Le mois n'est pas bon";
    }
    else {
        echo $months[$month - 1];
    }
}
afficherMois(3);
?>

And here is the error I am getting :

Notice: Undefined variable: months in C:\wamp64\www\VELO\date.php on line 16

Line 16 corresponding to : echo $months[$month - 1];

7bmax
  • 47
  • 6

1 Answers1

2

You can't echo the variable months inside the function as it was defined outside, which is a different scope.

You could add a second parameter, passing the $months variable into the function so you can use it's contents

function afficherMois($month, $months){
    if ($month < 1 || $month > 12){
        echo "Le mois n'est pas bon";
    }
    else {
        echo $months[$month - 1]; // Will be defined now
    }
}
atymic
  • 3,093
  • 1
  • 13
  • 26