What is the best way to verify that an element is ready for use in a foreach () loop in php?

example:

foreach($boxes as $box) {
    echo "$box \n";
}

Used to be fairly simple, I could just wrap the foreach around a check, for example:

if(is_array($boxes) && count($boxes) > 0) {
    //foreach loop here
}

There is no need to worry that you will receive a warning if for some reason bad input has been passed into the $ boxes array.

When iterators were added to the mix, this no longer works, since Iteratable objects are not arrays. So, I have several solutions, but I am wondering if there is a “best practice” for this.

// 1:
if($boxes instanceof Traversable && count($boxes) > 0) {
    //foreach loop here
}

// 2:
if($boxes && count($boxes) > 0) {
    //foreach loops here
}

There are others, but they seem most obvious. Anyone have any suggestions. PHP docs seem quiet.

+3
source share
5 answers

count($array) > 0 part, a) foreach , b) Traversable Countable c) , count(), ( ) .

# 1 # 2; $boxes instanceOf Traversable $boxes. , Traversable.

if (is_array($boxes) || $boxes instanceof Traversable) {
    foreach (...)
}

, ; . , .

+4

, , , , , .., :

if ($boxes) {
    foreach ($boxes as $box) {}
}

, ,

+2

One possibility depending on your php version is listing:

<?php

$a = array('foo', array('bar'));

foreach ($a as $thing)
  foreach ((array) $thing as $item) // <-- here
    echo "$item\n";
?>
0
source

This test will give true for both arrays and objects of type array

if (is_array($obj) || $obj instanceof Traversable) {
    foreach ($obj as $item) { /* foreach loop is safe here */
    }
}
0
source

In PHP5, you can iterate over any array or object in this way.

if (is_array($my_var) || is_object($my_var)) {
    // Do some foreachin'
}
0
source

Source: https://habr.com/ru/post/1757715/


All Articles