Hello,

I've an array with different type of values: int, null, strings, arrays. I'm trying to remove nulls and empty strings, but I want to save ints, even when it equals to zero, so I tried with array_filter(), by default it will remove 0, '' and null, but by applying a callback it's possible to apply own rules. So I made few tests, and I'm getting unexpected results. The switch method will remove null and 0, while the if statements will remove the empty string and null, as I wanted. Now, I can use the if statements, but I don't understand why there's this difference between the two methods, even by removing the breaks it won't change results.

Any ideas why this is happening?

<?php

$array = array(
    0,                      # int
    null,                   # null
    '',                     # empty string
    'hello',                # string
    array('world')          # array
    );

$r['original'] = $array;

$r['switch_method'] = array_filter($array, function($value) {
    switch($value)
    {
        case is_string($value):
            return ! empty($value);
            break;
        case is_int($value):
            return true;
            break;
        case is_null($value):
            return false;
            break;
        case is_array($value):
            return count($value);
            break;
        default:
            return false;

    }
});

$r['ifelseif_method'] = array_filter($array, function($value) {

    if(is_string($value))
    {
        return ! empty($value);
    }

    elseif(is_int($value))
    {
        return true;
    }

    elseif(is_array($value))
    {
        return true;
    }

    elseif(is_null($value))
    {
        return false;
    }

    else
    {
        return false;
    }

});

var_dump($r);
echo PHP_EOL;

This is the output:

array(3) {
  ["original"]=>
  array(5) {
    [0]=>
    int(0)
    [1]=>
    NULL
    [2]=>
    string(0) ""
    [3]=>
    string(5) "hello"
    [4]=>
    array(1) {
      [0]=>
      string(5) "world"
    }
  }
  ["switch_method"]=>
  array(3) {
    [2]=>
    string(0) ""
    [3]=>
    string(5) "hello"
    [4]=>
    array(1) {
      [0]=>
      string(5) "world"
    }
  }
  ["ifelseif_method"]=>
  array(3) {
    [0]=>
    int(0)
    [3]=>
    string(5) "hello"
    [4]=>
    array(1) {
      [0]=>
      string(5) "world"
    }
  }
}

Thank you for your attention.

I found this thread on the topic, which makes sense. switch tries to validate $value and skips if it thinks it's false. Use switch (true) and both outputs are the same.

commented: perfect! +11

Many thanks, now it works fine :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.