Ajwad Syed
Ajwad Syed

Reputation: 345

How to collect dates with respect to specific date value in php?

I want to show a message for customer about expiry amount which is expiring this month, so that he can renew it. Renew time starts from the last month of that expiring amount, that is:

$renewDate = date("Y-m-d", strtotime("-1 month", $currentdate));

I have

Expiry date: Amount

2019-11-31: 15

2019-11-22: 20

2020-5-12: 30

2019-11-2: 10

How can I collect only those amounts which are not less than renew date and are within the range of last one month.

Upvotes: 1

Views: 140

Answers (2)

Ajwad Syed
Ajwad Syed

Reputation: 345

By playing with @Angel answer I figured it out:

  $arr = [
      0=>[
        'date' => '2019-12-1',
        'amount' => 15
      ],
      1=>[
        'date' => '2019-11-31',
        'amount' => 22
      ],
      2=>[
        'date' => '2019-11-27',
        'amount' => 22
      ],
        3=>[
        'date' => '2019-11-12',
        'amount' => 33
      ],
        4=>[
        'date' => '2019-10-2',
        'amount' => 6
      ],
    ];

    $data = [];
    foreach ($arr as $key => $value) {
       if(strtotime(date('Y-m-d')) <= strtotime($value['date']) && 
  strtotime(date('Y-m-d').'+1 month') >= strtotime($value['date']))
       {
          $data[] = $value;
       }
    }
    echo "<pre>";
    print_r($data);
    echo "<pre>";

Upvotes: 0

Angel Deykov
Angel Deykov

Reputation: 1227

Lets assume you have an array with expiration dates:

$arr = [
  0=>[
    'date' => '2019-12-31',
    'amount' => 15
  ],
  1=>[
    'date' => '2019-12-22',
    'amount' => 22
  ],
    2=>[
    'date' => '2020-5-12',
    'amount' => 33
  ],
    3=>[
    'date' => '2019-10-2',
    'amount' => 6
  ],
];

Then we loop through the array, get each date and convert it with strtotime() by substract 1 month and compare it against 2 condition - if date is bigger than strtotime() of todays date and smaller than strtotime() of todays date +1 month we meet the range condition and save the data:

$data = [];
foreach ($arr as $key => $value) {
   if(strtotime(date('Y-m-d')) <= strtotime($value['date'].'-1 month') && 
      strtotime(date('Y-m-d').'+1 month') >= strtotime($value['date'].'-1 month'))
   {
      $data[] = $value;
   }
}

var_dump($data);

Upvotes: 1

Related Questions