Stefano Radaelli
Stefano Radaelli

Reputation: 1118

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. 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?

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...

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. And I want to exclude null values.

Upvotes: 1

Views: 15617

Answers (2)

Blackbam
Blackbam

Reputation: 19396

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 ;-)

Upvotes: 4

Martin
Martin

Reputation: 22770

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.

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.

Upvotes: 3

Related Questions