[英]php how to insert an element into array if is not null
I need to fill an array with a list of elements only if value is not null.仅当 value 不为 null 时,我才需要用元素列表填充数组。 Is there a way to skip the array filling if value to be appended is null?如果要附加的值为空,有没有办法跳过数组填充?
As example:例如:
$list = array();
for ($i = 1; $i <= 10; $i++) {
$modulo = ($i % 2);
if ($modulo) $list[] = $i;
}
Is there a way to write the two statement in the loop into an unique one without using $modulo variable ?有没有办法在不使用 $modulo 变量的情况下将循环中的两个语句写入唯一的语句?
something like...就像是...
$list = array();
for ($i = 1; $i <= 10; $i++) {
$list[] = ($i % 2);
}
The expected behavior is that $list array has to contain 1,3,5,7,9...预期的行为是 $list 数组必须包含 1,3,5,7,9 ...
This is not the real example as the ($i % 2) has to be replaced with a complex function applied on an array of 380k elements and may return something or null.这不是真正的例子,因为 ($i % 2) 必须用一个复杂的函数替换,该函数应用于 380k 元素的数组,并且可能返回某些内容或 null。 And I want to exclude null values.我想排除空值。
How about being cool like this:像这样酷怎么样:
$list = [];
for ($i = 1; $i <= 10; $i++) {
($i%2) ? ($list[] = $i) : "";
}
However its a bit confusing how you describe it.但是,您如何描述它有点令人困惑。 Maybe you want:也许你想要:
$list = [];
for ($i = 1; $i <= 10; $i++) {
(!is_null($i%2)) ? ($list[] = $i) : "";
}
Or if you want the result of the function:或者,如果您想要函数的结果:
$list = [];
for ($i = 1; $i <= 10; $i++) {
(!is_null($a = ($i%2))) ? ($list[] = $a) : "";
}
It must be one of these ;-)它必须是其中之一;-)
One:一:
$list = array();
for (i = 1; $i <= 10; $i++) {
$modulo = ($i % 2);
if (!is_null($modulo)){
$list[] = $i;
}
}
If the value is not a PHP null
then you can add it to the $list
array.如果该值不是 PHP null
那么您可以将其添加到$list
数组中。
Two:二:
$list = array();
for (i = 1; $i <= 10; $i++) {
$list[] = $i;
}
$list = array_filter($list);
PHP array_filter
will remove any falsey
or null
or empty
values from the array, if this fits what possible values you have. PHP array_filter
将从数组中删除任何falsey
或null
或empty
值,如果这适合您拥有的可能值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.