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!
if (!empty($array)){
foreach ($array as $val)
echo $val;
}
else
echo "array is empty";
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.
if (count($i) > 0) {
foreach ($i as $x) { ... }
} else {
echo 'i is empty';
}
assuming i
is an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With