Asez Asez - 3 months ago 8
PHP Question

PHP: Function with 3 arguments > Use it with less arguments

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.

Answer

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