php 如果数组为空,则跳过 foreach 的最干净方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3446538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:48:09  来源:igfitidea点击:

cleanest way to skip a foreach if array is empty

phpcoding-style

提问by Keyo

Not a major problem but I was wondering if there is a cleaner way to do this. It would be good to avoid nesting my code with an unnecessary if statement. If $itemsis empty php throws an error.

不是大问题,但我想知道是否有更清洁的方法来做到这一点。最好避免使用不必要的 if 语句嵌套我的代码。如果$items为空,则 php 会引发错误。

$items = array('a','b','c');

if(!empty($items)) { // <-Remove this if statement
  foreach($items as $item) {
    print $item;
  }
}

I could probably just use the '@' error suppressor, but that would be a bit hacky.

我可能只使用 '@' 错误抑制器,但这有点麻烦。

回答by Christian

There are a million ways to do this.

有一百万种方法可以做到这一点。

The first one would be to go ahead and run the array through foreach anyway, assuming you do have an array.

第一个是继续并通过 foreach 运行数组,假设您确实有一个数组。

In other cases this is what you might need:

在其他情况下,这就是您可能需要的:

foreach ((array) $items as $item) {
    print $item;
}

Note:to all the people complaining about typecast, please note that the OP asked cleanest way to skip a foreach if array is empty(emphasis is mine). A value of true, false, numbers or strings is not considered empty. In addition, this would work with objects implementing \Traversable, whereas is_arraywouldn't work.

注意:对于所有抱怨类型转换的人,请注意 OP 要求以最干净的方式跳过 foreach 如果数组为(重点是我的)。值 true、false、数字或字符串不被视为空值。此外,这适用于实现 的对象\Traversable,而is_array不起作用。

回答by Matt Williamson

$items = array('a','b','c');

if(is_array($items)) {
  foreach($items as $item) {
    print $item;
  }
}

回答by Your Common Sense

The best way is to initialize every bloody variablebefore use.
It will not only solve this silly "problem" but also save you a ton of realheadaches.

最好的方法是在使用前初始化每个该死的变量
它不仅可以解决这个愚蠢的“问题”,还可以为您省去一大堆真正的麻烦。

So, introducing $items as $items = array();is what you reallywanted.

因此,按$items = array();真正想要的方式引入 $items 。

回答by Zach Rattner

I wouldn't recommend suppressing the warning output. I would, however, recommend using is_arrayinstead of !empty. If $itemshappens to be a nonzero scalar, then the foreachwill still error out if you use !empty.

我不建议抑制警告输出。但是,我建议使用is_array而不是!empty. 如果$items碰巧是一个非零标量,那么foreach如果您使用!empty.

回答by Daniel Kmak

If variable you need could be boolean false- eg. when no records are returned from databaseor array- when records are returned, you can do following:

如果您需要的变量可能是boolean false- 例如。当没有从数据库返回记录array-当返回记录时,您可以执行以下操作:

foreach (($result ? $result : array()) as $item)
    echo $item;

Approach with cast((Array)$result) produces an array of count 1 when variable is boolean falsewhich isn't what you probably want.

(Array)$result当变量boolean false不是您可能想要的时,使用 cast( ) 的方法会生成一个计数为 1 的数组。

回答by Vladislav Rastrusny

I think the best approach here is to plan your code so that $items is always an array. The easiest solution is to initialize it at the top of your code with $items=array(). This way it will represent empty array even if you don't assign any value to it.

我认为这里最好的方法是规划您的代码,以便 $items 始终是一个数组。最简单的解决方案是在代码顶部使用 $items=array() 对其进行初始化。这样,即使您没有为其分配任何值,它也将表示空数组。

All other solutions are quite dirty hacks to me.

所有其他解决方案对我来说都是非常肮脏的黑客。

回答by Milan

foreach((array)$items as $item) {}

回答by user187291

i've got the following function in my "standard library"

我的“标准库”中有以下功能

/// Convert argument to an array.
function a($a = null) {
    if(is_null($a))
        return array();
    if(is_array($a))
        return $a;
    if(is_object($a))
        return (array) $a;
    return $_ = func_get_args();
}

Basically, this does nothing with arrays/objects and convert other types to arrays. This is extremely handy to use with foreach statements and array functions

基本上,这对数组/对象没有任何作用,而是将其他类型转换为数组。这对于与 foreach 语句和数组函数一起使用非常方便

  foreach(a($whatever) as $item)....

  $foo = array_map(a($array_or_string)....

  etc

回答by swirt

Ternary logic gets it down to one line with no errors. This solves the issue of improperly cast variables and undefined variables.

三元逻辑将它归结为一行,没有错误。这解决了不正确地转换变量和未定义变量的问题。

foreach (is_array($Items) || is_object($Items) ? $Items : array()  as $Item) {

It is a bit of a pain to write, but is the safest way to handle it.

写起来有点痛苦,但却是最安全的处理方式。

回答by spetsnaz

Best practice is to define variable as an array at the very top of your code.

最佳实践是在代码的最顶部将变量定义为数组。

foreach((array)$myArr as $oneItem) { .. }

foreach((array)$myArr as $oneItem) { .. }

will also work but you will duplicate this (array) conversion everytime you need to loop through the array.

也可以工作,但每次需要循环遍历数组时,都会重复此(数组)转换。

since it's important not to duplicate even a word of your code, you do better to define it as an empty array at top.

因为重要的是不要复制代码中的一个字,所以最好将其定义为顶部的空数组。