S S
S S

Reputation: 1503

Remove items of the array before the current year

I have an array containing some dates in following format. I want to remove the items with key before 2019 year.

This is the code I have tried so far. But I am not getting any result.

Can anybody please help me.

$array = [
  "date_2018_08" => 81,
  "date_2018_09" => 70,
  "date_2018_10" => 70,
  "date_2018_11" => 95,
  "date_2018_12" => 75,
  "date_2019_01" => 91,
  "date_2019_02" => 78,
  "date_2019_03" => 95,
  "date_2019_04" => 68
];
$year = 2019;
$month = 4;


$array = array_filter($array,function($date){
    $t1 = strtotime(str_replace(["date_", "_"], ["", "-"], $date));
    return $t1 >= strtotime(str_replace(["date_", "_"], ["", "-"], '2019-01-01'));
});

Upvotes: 2

Views: 50

Answers (2)

dWinder
dWinder

Reputation: 11642

You can use array_filter (doc) with flag "ARRAY_FILTER_USE_KEY" as:

$year = 2019;
$filtered = array_filter(
    $array,
    function ($key) use ($year) {
        $parts = explode("_", $key);
        return $parts[1] >= $year;
    },
    ARRAY_FILTER_USE_KEY
);

Live example: 3v4l

Edited:

Using simple foreach:

foreach($array as $k => $v) {
    $parts = explode("_", $k);
    if ($parts[1] >= $year)
        $filtered[$k] = $v;
}

Upvotes: 1

Rahul
Rahul

Reputation: 18557

Demo link.

You can pass $year and $month to filter out the array,

$year  = 2019;
$month = str_pad(4,2,"0",STR_PAD_LEFT); // pad to left with zero to match string
$temp  = array_filter($array, function ($key) use ($year, $month) {
    return (strpos($key, $year . "_" . $month) === false);
}, ARRAY_FILTER_USE_KEY);
print_r($temp);die;

strpos — Find the position of the first occurrence of a substring in a string
array_filter — Filters elements of an array using a callback function
str_pad — Pad a string to a certain length with another string

Note: ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value

Upvotes: 1

Related Questions