0

So I just started with Coding like 2 weeks ago and I Need to make a function that gives back how much time ago a given date was but only in months and years together with two textfields to type the time in and a submit button and I have something but it doesnt quite work and I think I made mistakes aswell.

I want to be able to type in year and month into the textfields and when Pressing submit have them go through the function which then gives out the time ist been since the given date in numbers like "it's been 03 months and 03 years"

<?php
function timeago(int $month, int $year)
{

 $month = date('m') - $month;
 $year = date('Y') - $year;

  $year = sprintf("%02d", $year);
  $month = sprintf("%02d", $month);

 $since = array($month, $year);

  return $since;
}

echo '<form method="post" action="">
      Month: <input type="text" name="month" maxlength="2" /><br>
      Year: <input type="text" name="year" maxlength="4" /><br>
      <input type="submit" name="btn_submit" value="submit" />
      </form>';

echo $since;
echo timeago($_POST['month'], $_POST['year']);
?>

This is what I get so far:

Notice: Undefined variable: since in C:\Users\Documents\PHP Files\test.php on line 27

Notice: Undefined index: month in C:\Users\Documents\PHP Files\test.php on line 28

Notice: Undefined index: year in C:\Users\Documents\PHP Files\test.php on line 28

Fatal error: Uncaught TypeError: Argument 1 passed to timeago() must be of the type int, null given, called in C:\Users\Documents\PHP Files\test.php on line 28 and defined in C:\Users\Documents\PHP Files\test.php:2 Stack trace: #0 C:\Users\Documents\PHP Files\test.php(28): timeago(NULL, NULL) #1 {main} thrown in C:\Users\Documents\PHP Files\test.php on line 2

Mana
  • 11
  • 1
  • One thing to that is always useful is when you say *but it doesnt quite work* is to explain what you mean by that. – Nigel Ren May 28 '20 at 08:14
  • 1
    Please go read [ask]. You need to give us a _proper_ problem description. Include example data, what result you _expected_ based on that, and what you are actually getting. – CBroe May 28 '20 at 08:15
  • You did not declare any variable named `$since` in that context where you try to echo it. And regarding the undefined index notices, please go read https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined – CBroe May 28 '20 at 08:37
  • you have to execute the function once the form is submitted, not on initial load – Kevin May 28 '20 at 08:46

0 Answers0