开发者

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 actual开发者_如何学Cly 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.


Doing exact implementation as the python manual says is this:

$count = count($my_array);
$cntr = 0;
foreach($my_array as $my_value)
{
  $cntr++;
  // do the loop work
}
if($cntr == $count)
{
   // all elements treated, do the 'python-else' part.
}


I realize this does not answer your specific example, but I have used goto as a workaround for another for -> else Python to PHP problem:

foreach(range(2,100) as $n){
    for($x = 2; $x < $n; $x++){
        if($n % $x==0){
            print $n . ' equals ' . $x . ' * ' . $n/$x . '<br>';
            goto end;   
        }
    }
        echo $n . ' is a prime number.<br>';    
        end:
    }

Perhaps this is a more practical answer.


Sadly there is no such thing as forelse loop in PHP, but if you are using laravel, in their blade templating engine they have a forelse loop that goes something like this

@forelse($arrays as $string)
  <p>{{ $string }}</p>
@empty
  <p>Empty</p>
@endforelse

Further information here -> https://laravel.com/docs/5.4/blade#loops

but you can make a work around if you are not using laravel's blade templating engine, something like this would be a great approach

if(count($arrays)) {
  foreach($arrays as $string) {
    echo '<p>'. $string .'</p>';
  }
} else {
  echo '<p>Empty!</p>';
}

if you came up with a better idea, beep me please.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜