Php内爆空数组[重复]

This question already has an answer here:

I have a simple array with no values assigned:

Array
(
    [field1] => 
    [field2] => 
)

then doing something like:

$result = array();
foreach ($array as $val) {
   array_push($result, $val);
}

$data = implode("::", $result);

I end up with:

::

So how can I prevent implode generating separator if array values are empty? If I have at least one value assigned:

Array
(
    [field1] => "hello"
    [field2] => 
)

Then implode does it's job fine.

</div>

You can use array_filter() , for example in your case:

implode( ':', array_filter( $result ) );

That will filter your array before imploding it.

Use array_filter() to filter the array (Removing empty elements) before you actually implode your array.

According to the docs for array_filter():

If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.

This means that (if you're dealing with only strings), '' or '0' will be removed. If 0 is a valid string in your $result, then use a custom callback function:

$result = array_filter($result, function($val) {
    return $val !== '';
});

Final Code:

$result = array(
    'field1' => '',
    'field2' => ''
);

$result = array_filter($result);

$data = implode("::", $result);

You can see it in action here.

EDIT: An alternative way, is to prevent empty values from getting into your array in the first place:

$result = array();
foreach ($array as $val) {
   if ( $val !== '' ) {
       array_push($result, $val);
   }
}