9
Array
    (
      [0] => 0   //value is int 0 which isn;t empty value
      [1] =>     //this is empty value
      [2] =>     //this is empty value
    )

I would like to make the above array to be as the following, Can anyone help me?

Many thanks

Array
    (
      [0] => 0
    )
hakre
  • 193,403
  • 52
  • 435
  • 836
Acubi
  • 2,793
  • 11
  • 41
  • 54
  • 7
    What are those empty values? Are they false, NULL, empty strings or something else? What about the 0? Is it the integer 0, or the string "0"? Use `var_dump()` on your array to determine the types of the values. – BoltClock Jan 30 '12 at 11:08

5 Answers5

20

You can use array_filter to remove empty value (null, false,'',0):

array_filter($array);

If you don't want to remove 0 from your array, see @Sabari's answer:

array_filter($array,'strlen');
Zul
  • 3,627
  • 3
  • 21
  • 35
  • 3
    Didn't know that the second argument is optional, that's neat. – Gajus Jan 30 '12 at 11:13
  • @Zulkhaery Basrul, array_filter would think value 0 is empty value, so final result is an empty array which isn't what i want – Acubi Jan 30 '12 at 11:14
  • As of PHP 8.1, strlen will now emit a deprecated error "strlen(): Passing null to parameter #1 ($string) of type string is deprecated" – Brad Kent Nov 30 '21 at 14:50
5

You can use:

To Remove NULL values only:

$new_array_without_nulls = array_filter($array_with_nulls, 'strlen');

To Remove False Values:

$new_array_without_nulls = array_filter($array_with_nulls);

Hope this helps :)

Sabari
  • 6,205
  • 1
  • 27
  • 36
  • As of PHP 8.1, strlen will now emit a deprecated error "strlen(): Passing null to parameter #1 ($string) of type string is deprecated" – Brad Kent Nov 30 '21 at 14:50
  • Also... the `strlen` callback would also remove empty string and `false` values (in addition to `null`) – Brad Kent Nov 30 '21 at 15:12
1
array_filter($array, function($var) {
    //because you didn't define what is the empty value, I leave it to you
    return !is_empty($var);
});
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

quick way to find numbers also Zero (0)

    var_dump(  
            array_filter( array('0',0,1,2,3,'text') , 'is_numeric'  )
        );
/* 
print :
array (size=5)
  0 => string '0' (length=1)
  1 => int 0
  2 => int 1
  3 => int 2
  4 => int 3

*/
abbasian
  • 1
  • 1
0

That's a typical case for array_filter. You first need to define a function that returns TRUE if the value should be preserved and FALSE if it should be removed:

function preserve($value)
{
    if ($value === 0) return TRUE;

    return FALSE;
}

$array = array_filter($array, 'preserve');

You then specify in the callback function (here preserve) what is empty and what not. You have not written in your question specifically, so you need to do it on your own.

hakre
  • 193,403
  • 52
  • 435
  • 836