Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Echoing date via german array causes error

So I´ve got this array, containing the german equivilant word for each month number (without leading zero):

$months= array(1=>"Januar",
               2=>"Februar",
               3=>"März",
               4=>"April",
               5=>"Mai",
               6=>"Juni",
               7=>"Juli",
               8=>"August",
               9=>"September",
               10=>"Oktober",
               11=>"November",
               12=>"Dezember");

Now I´m fetching the month 3 days ago:

$german = date("n", strtotime("-3 days"));

Echoing the value of $german in $months produces an error:

echo $month($german);

Error Message:

Fatal error: Function name must be a string in X on line X

Echoing $german alone doesn´t produce an error.
Echoing $months(date("n", strtotime("some $row value from database"))) doesn´t produce an error.
What´s the problem?
I already tried doing this: echo $months((int)$german), but this didn´t work either.

like image 548
3x071c Avatar asked Aug 06 '26 08:08

3x071c


2 Answers

In your associative array, you need to surround the keys with quotes.

Example:

$months = array("1" => "Januar",
                "2" => "Februar",
                "3" => "März",
                "4" => "April",
                "5" => "Mai",
                "6" => "Juni",
                "7" => "Juli",
                "8" => "August",
                "9" => "September",
                "10" => "Oktober",
                "11" => "November",
                "12" => "Dezember");

Further Thoughts:

Since your keys are numbers, you could forgo an associative array and simply use an indexed array:

$months = array("Neujahr",
                "Januar",
                "Februar",
                "März",
                "April",
                "Mai",
                "Juni",
                "Juli",
                "August",
                "September",
                "Oktober",
                "November",
                "Dezember");

From this indexed array:

  • array_search("Oktober", $months) gives 10.
  • $months[6] gives "Juni"
like image 79
Rounin - Glory to UKRAINE Avatar answered Aug 09 '26 00:08

Rounin - Glory to UKRAINE


$months is an array, not an function. When referencing an element in an array, you have to use [] and not () (which is used for calling a function or method).

echo $month[$german];

should work, while $month($german) tries to call a function stored in the variable $month.

like image 34
MatsLindh Avatar answered Aug 09 '26 00:08

MatsLindh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!