Search code examples
phploopsdate

Iterate over all last-day-of-the-month dates in a year


I have earlier asked this question but by mistake, I deleted the question so reposting it as another question.

if (isset($_REQUEST['Receipts'])) {
    $params['Date'] = '31 Jan 2000';
    $response = $Auth->request('GET', $Auth->url('Receipts/Travel', 'core'), $params);
    if ($Auth->response['code'] == 200) {
        $receipt = $Auth->parseResponse($OAuth->response['response'], $Auth->response['format']);
        pr($receipt->Receipts);
    } else {
        outputError($Auth);
    }
}

This piece of code provides me with the Travel receipts as on 31 Jan 2000 and now I wanted to include a foreach loop so that I could get Travel receipts for whole 12 months of 2000 like 28 Feb 2000, 31 Mar 2000 and so on till 31 Dec 2000.

I am a beginner and hence tried the following basic foreach loop which didn't work as I know I misplaced the logic.

if (isset($_REQUEST['Receipts'])) {
    $months = array(" 31 Jan 2000"," 28 Feb 2000"," 31 Mar 2000","30 Apr 2000","31 May 2000","30 Jun 2000","31 Jul 2000"," 31 Aug 2000","30 Sep 2000","31 Oct 2000","30 Nov 2000","31 Dec 2000");
    foreach ($months as $month){
        $params['Date'] = '31 Jan 2000';
        $response = $Auth->request('GET', $Auth->url('Receipts/Travel', 'core'), $params);
        if ($Auth->response['code'] == 200) {
            $receipt = $Auth->parseResponse($OAuth->response['response'], $Auth->response['format']);
            pr($receipt->Receipts);
        } else {
            outputError($Auth);
        }
    }
}

Is there any way that instead of directly storing month values[ 31 Jan 2000"," 28 Feb 2000"," 31 Mar 2000"...] in an array, the code itself should increment for different months. Because providing all the month values of a year is kind of hardcoding and for other years I need to edit it often.


Solution

  • You used foreach but must've forgot to plug it into the $params variable.

    foreach ($months as $month){
       $params['Date'] = $month;
    ...
    }
    

    Does it solve the problem?