1

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.

2
  • You could just use the evaluation expression in your if statement. Commented Feb 10, 2017 at 15:44
  • 3
    Once you fix the parse errors, your code produces 1,3,5,7,9, so I don't get it. Commented Feb 10, 2017 at 15:47

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

Also note that using array_filter will not give you sequential keys on the result array, so you might want to wrap it with array_values too in case the rest of the code depends on the array keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.