Array not returning correct value

Alex

I'm currently trying to apply text to whether the events inside my event group have spaces available or are sold out.

My loop looks at each event in the event group and returns whether they are sold out or available for each specific event. My issue is that it's just returning the same value for both events rather than looking at each specific event so it is returning the wrong value.

It adds these to an array and implodes each one out, but the second value is always wrong. Any ideas?

Even if the second event has hit it's capacity value, it still shows as available

public function getAreEventsAvailableStringMultiple() {
    $availability = null;
    foreach ($this->events as $event) {
        $availability[] = $this->getAreEventsAvailable() ? 'Spaces still available' : 'Sold Out';
    }
    return implode(' <br/> ', $availability);
}

Other function

 public function getAreEventsAvailable() {
        foreach ($this->events as $event) {
            if ($event->getRemainingCapacity() > 0) {
                return true;
            }
        }
        return false;
    }
Jakub Krawczyk

You are iterating over $this->events (which is probably an array of event objects), but checking availability for $this, meaning the current object.

If $this->events is array of objects, then you should do this:

   foreach ($this->events as $event) {
       $availability[] = $event->getAreEventsAvailable() ? 'Spaces still available' : 'Sold Out';
   }

Assuming that your Event object has getAreEventsAvailable() method.

If $this->getAreEventsAvailable() returns availability for all the events, there is no need for the foreach loop, just assign the result to $availability:

$availability = $this->getAreEventsAvailable();

EDIT: Your getAreEventsAvailable() should look like this:

public function getAreEventsAvailable() {
    $availability = [];

    foreach ($this->events as $event) {
        if ($event->getRemainingCapacity() > 0) {
            $availability[] = true;
        } else {
            $availability[] = false;
        }
    }

    return $availability;
}

and then in your getAreEventsAvailableStringMultiple() function:

public function getAreEventsAvailableStringMultiple() {
    $availability = [];

    foreach ($this->getAreEventsAvailable() as $eventAvailable) {
        $availability[] = $eventAvailable ? 'Spaces still available' : 'Sold Out';
    }
    return implode(' <br/> ', $availability);
}

It is not the most ellegant solution, but it should work.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related