Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling null loops in php

Python offers a for...else structure [but not] like this:

for value in i:
    print value
else:
    print 'i is empty'

What's the nearest equivalent to this in PHP?

Edit: see @Evpok's comment below - the for...else doesn't actually work as the print statements suggest it does. My mistake - sorry!

like image 727
Ollie Glass Avatar asked Aug 11 '11 14:08

Ollie Glass


3 Answers

if (!empty($array)){
   foreach ($array as $val)
        echo $val;
}
else
    echo "array is empty";
like image 90
J0HN Avatar answered Nov 07 '22 10:11

J0HN


To account for all traversables, including uncountable ones, the correct approach would be:

$iterated = false;
foreach ($traversable as $value) {
    $iterated = true;

    echo $value;
}

if (!$iterated) {
    echo 'traversable is empty';
}

If you are writing generalized code this is the way to go. If you know that you will get a countable traversable, the count method is obviously nicer to read.

like image 31
NikiC Avatar answered Nov 07 '22 09:11

NikiC


if (count($i) > 0) {
   foreach ($i as $x) { ... }
} else {
   echo 'i is empty';
}

assuming i is an array.

like image 4
Marc B Avatar answered Nov 07 '22 10:11

Marc B