To check whether an array to foreach?

To avoid exceptions and errors since php 5 always do the test view:
$data = $this->orderRepository->getList();

if ($data) {
 foreach ($data as $datum) {
}
}


Is it important to php 7.(0,1,2)?

upd: changed the code to make it more clear.
upd 2: I came to the conclusion that the getList must return only an array (or collection).
Symphony as an example:
class EntityRepository implements ObjectRepository, Selectable
{
/**
 * Finds entities by a set of criteria.
 * ...
 * @return array The objects.
*/
 public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
{
}
}
June 5th 19 at 21:54
4 answers
June 5th 19 at 21:56
$this->orderRepository->getList();

If getList returned null instead of an empty iterable object, then it's IMHO a wrong design of the getList
but this is a very good point - lily.Kozey commented on June 5th 19 at 21:59
June 5th 19 at 21:58
No. Foreach is executed only when the array has data.
Yeah, about that know. Want to know exactly how to do it better. - lily.Kozey commented on June 5th 19 at 22:01
June 5th 19 at 22:00
Here was the answer . I'll bring him because he already started to answer

Excuse me, but why you did that? And nothing like the exceptions, what they are for? If an array of something, then catch the exception and handle it.
Of course the fear of exceptions. Now not so much :) and don't remember exceptions for foreach in the latest versions of php.

For example, there is a method that prints pdf documents. There may be many, and may not be at all. And this is not an exceptional situation. Can't even see where it is better to handle the exception. - lily.Kozey commented on June 5th 19 at 22:03
I answer and deleted because I realized that not understood you correctly :) at First I thought you input data from the user test. - meggie commented on June 5th 19 at 22:06
June 5th 19 at 22:02
The idea getList() needs to return a collection, which must be objects of the expected class (if in a loop you will call some methods of the objects, it will protect from NPE), then you can write:
$data = $this->orderRepository->getList();

if ($data instanceof OrderCollection) {
 foreach ($data as $datum) {
}
}

Find more questions by tags PHP