0

I'm stuck in my php script for a blog where I want to display the time and date for all the articles. I created a function but I don't know why it doesn't want to work:

function articles(){ 
    global $bdd;

    $articles = $bdd->query("SELECT id, titre, accroche, contenu, publication, image FROM articles");
    $articles = $articles->fetchAll();

    return $articles;
}

function formattage_date($publication){ 
    $publication = explode(" ", $publication);
    $date = explode("-", $publication[0]);
    $heure = explode(":", $publication[1]);

    $mois = ["", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];

    $resultat = $date[2] . ' ' . $mois[$date[1]] . ' ' . $date[0] . ' à ' . $heure[0] . 'h' . $heure[1];

    return $resultat;


}

When I want to use $mois, php says: Notice: Undefined index: 03 in C:\wamp\www\entertheletter.dev\fonctions\blog.php on line 18

alkasm
  • 22,094
  • 5
  • 78
  • 94
imbecco
  • 11
  • 1
  • 2
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/q/4261133/6521116) – LF00 Jun 08 '17 at 10:27

2 Answers2

1

Your problem is the following;

$mois[$date[1]]

The date string from the database is zerofilled if the value is below 10. So assume that the month is january (janvier), you get 01 instead of 1. When accessing the $mois array with that index, it is not able to find it because 01 is not a valid index.

To fix this, remove the first 0 if the date is zerofilled. Or just cast it to int like

$mois[(int)$date[1]]
KarelG
  • 5,176
  • 4
  • 33
  • 49
0

you can try this function where i have added ltrim function in $mois array we have to converted 01 to 0 because array index start from 0,1,2 ...

so we have to remove 0 from 01.

 function formattage_date($publication){ 
  $publication = explode(" ", $publication);
  $date = explode("-", $publication[0]);
  $heure = explode(":", $publication[1]);

  $mois = ["", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];


  $resultat = $date[2] . ' ' . $mois[ltrim($date[1],0)] . ' ' . $date[0] . ' à ' . $heure[0] . 'h' . $heure[1];

return $resultat;


}
Bhavin Thummar
  • 1,255
  • 1
  • 12
  • 29