Subtlebot
Subtlebot

Reputation: 322

Array values replaced rather than pushed

I'm trying to build a multidimensional array like array(years => array(months)). Each new month added to a year replaces the old month value in the year array rather than appending the value.

<?php 
$dates = array();
foreach (Blog::all() as $blog) {
    $date_year = date("Y", strtotime($blog->created_at));
    $date_month = date("F", strtotime($blog->created_at));
    if (!in_array($date_year, $dates)) {
        $dates[$date_year] = array();
    }
    if (!in_array($date_month, $dates[$date_year])) {
        $dates[$date_year][] = $date_month;
        print $date_year." ".$date_month."<br>";
    }
}
print_r($dates); ?>

Outputs:

Array ( [2009] => Array ( [0] => December ) [2010] => Array ( [0] => March ) [2011] => Array ( [0] => August ) [2012] => Array ( [0] => November ) [2013] => Array ( [0] => October ) [2014] => Array ( [0] => April ) )

The months displayed are the last month available for each year. I have also tried with array_push($dates[$date_year], $date_month) for the same result.

Upvotes: 0

Views: 52

Answers (1)

Leng
Leng

Reputation: 2998

The year array is being overwritten each time here:

if (!in_array($date_year, $dates)) {
    $dates[$date_year] = array();
}

Check the array keys instead of the array values with array_key_exists:

if (!array_key_exists($date_year, $dates)) {
    $dates[$date_year] = array();
}

Or, better yet IMO, use isset as suggested by vp_arth below. (For succintness.)

if (!isset($dates[$date_year])) {
    $dates[$date_year] = array();
}

Upvotes: 3

Related Questions