Reputation: 179
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.
Upvotes: 1
Views: 423
Reputation: 13344
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 ) );
}
Upvotes: 3
Reputation: 33993
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
Upvotes: 3