chloe
chloe

Reputation: 115

Show duplicate elements from an array

I'm making a calender and want to show elements (public holiday etc.) from array.

$holidays = Array (
    "20130101" => "New Year's Day",
    "20130101" => "School Holiday",
    "20130126" => "Australia Day",
...
);

$today = '20130101';
foreach ($holidays as $key => $val) {
    if ($today == $key) echo $val; else;
}

But it only shows "School Holiday" which is the last element in the array but I want to show both "New Year's Day" and "School Holiday".

Any advice on how to approach this problem? Thank you in advance.

Upvotes: 0

Views: 88

Answers (3)

ikos23
ikos23

Reputation: 5364

You can't compare strings by using == operator. Try this one !

$holidays = Array (
    "20130101" => "New Year's Day",
    "20130101" => "School Holiday",
    "20130126" => "Australia Day",
    ...
);

$today = '20130101';
foreach ($holidays as $key => $val) {
     if (strcmp($today,$key) == 0) echo $val; else;
}

Upvotes: 0

Tomalak
Tomalak

Reputation: 338416

You cannot have two elements with the same key in an array. This:

$holidays = Array (
    "20130101" => "New Year's Day",
    "20130101" => "School Holiday",
    "20130126" => "Australia Day"
);

evaluates to

[
    "20130101" => "School Holiday",
    "20130126" => "Australia Day"
]

so it's no surprise that you only get one result in your loop.

Consider something like this:

$holidays = Array (
    Array ("date" => "20130101", "name" => "New Year's Day"),
    Array ("date" => "20130101", "name" => "School Holiday"),
    Array ("date" => "20130126", "name" => "Australia Day")
);

$today = '20130101';

foreach ($holidays as $holiday) 
{
    if ($holiday["date"] == $today) 
    {
        echo $holiday["name"] . "\n";
    }
}

Upvotes: 0

bwoebi
bwoebi

Reputation: 23787

You could create an array for each entry in this format as array keys must be unique:

$holidays = Array (
    "20130101" => array (
                         "New Year's Day",
                         "School Holiday",
                  ),
    "20130126" => array("Australia Day"),
...
);

if (isset($holidays[$today]))
    echo implode(", ", $holidays[$today]);

Also you don't have to use a big loop, a direct array access is enough.

Upvotes: 1

Related Questions