1

I just created a function to add years|months|days to date. But I have a small issue, sometimes I want to add just years, but since the function has 3 arguments (years,months, days), I get a warning:

Warning: Missing argument 2 for addDate(), called in C:\xampp\htdocs\date.php on line 10 and defined in C:\xampp\htdocs\date.php on line 2

Warning: Missing argument 3 for addDate(), called in C:\xampp\htdocs\date.php on line 10 and defined in C:\xampp\htdocs\date.php on line 2

<?php 
function addDate($years, $months, $days)
{
    $currentDate = date('Y-m-d');

    $newDate = date('Y-m-d', strtotime($currentDate. '+'. $years. ' years +'. $months. ' months +'. $days. ' days'));
    echo $newDate;
}

addDate(2);
?>

I've tried to use addDate(2, null, null); but It doesn't work.

3
  • Set default values in your function definition: function addDate($years, $months = 0, $days = 0) Commented Aug 29, 2016 at 22:02
  • addDate(2, 0, 0); should work without editing the function. But the best solution is to use default values as others suggest Commented Aug 29, 2016 at 22:05
  • If you want to add only days for example, you'll need addDate(0, 0, 2) regardless. Commented Aug 29, 2016 at 22:15

2 Answers 2

3

You can declare default values for parameter:

function addDate($years, $months = 0, $days = 0)

This way you don't need to specify those or call your function like 'addDate(2,0,0)'

See http://php.net/manual/functions.arguments.php

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

Comments

3

You can define a default value for the parameter, like,

function addDate($years = 0, $months = 0, $days = 0)
{

Might be better to check whether each is >0 before building the string:

$newDateString = '';
if ( $years > 0 ) $newDateString .= " +$years years";
if ( $months > 0 ) $newDateString .= " +$months months";
if ( $days > 0 ) $newDateString .= " +$days days";
$newDate = date('Y-m-d', strtotime( date('Y-m-d') . $newDateString ) );

Lastly, you will (probably) want to be passing the value back using return rather than echo()ing - allows for more versatility later down the line:

    return $newDate;

And calling it like so:

echo addDate( 2 );

Function altogether:

function addDate($years = 0, $months = 0, $days = 0)
{
    $newDateString = '';
    if ( $years > 0 ) $newDateString .= " +$years years";
    if ( $months > 0 ) $newDateString .= " +$months months";
    if ( $days > 0 ) $newDateString .= " +$days days";
    return date('Y-m-d', strtotime($currentDate . $newDateString ) );
}

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.