I am trying to show only the items on my list that have not been ticked off. I have 7 items on the list and I have only ticked off one, so I should see the other 6 items on the list. I am having some difficulty figuring that out though. Any ideas would be helpful!
foreach ($list->getItems() as $item) {
if ($item->isCompleted() == isset($item)) {
echo $item->isCompleted() .PHP_EOL;
}
When I run this code in the terminal I get 1, which makes sense cause there is only one item on the list that is set with a value.
class ShoppingListDetailModel implements IteratorAggregate, Countable
{
/**
* @var string
*/
private string $slug;
/**
* @var string
*/
private string $name;
/**
* @var ShoppingItemDetailModel[]
*/
private array $items = [];
/**
* ShoppingListDetailModel constructor.
*
* @param string $slug
* @param string $name
* @param array $items
*/
public function __construct(string $slug, string $name, array $items)
{
$this->slug = $slug;
$this->name = $name;
$this->addItems($items);
}
/**
* @return string
*/
public function getSlug(): string
{
return $this->slug;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return ShoppingItemDetailModel[]
*/
public function getItems(): array
{
return $this->items;
}
/**
* @inheritDoc
*/
public function getIterator(): Generator
{
yield from $this->items;
}
/**
* @inheritDoc
*/
public function count(): int
{
return count($this->items);
}
/**
* @return bool
*/
public function isEmpty(): bool
{
return empty($this->items);
}
/**
* @param array $items
* @return void
*/
private function addItems(array $items): void
{
foreach ($items as $item) {
if ($item instanceof ShoppingItemDetailModel) {
$this->items[] = $item;
continue;
}
throw new RuntimeException('Expecting only shopping item detail models.');
}
}
}
CodePudding user response:
foreach ($list->getItems() as $item) {
if (!$item->isCompleted()) {
echo sprintf(
"%s. [%s] %s",
$item->getId(),
$item->isCompleted(),
$item->getName(),
) . PHP_EOL;
}
CodePudding user response:
Why do not use something like :
array_filter($list->getItems(), fn($item) => $item->isCompleted() === false);