1

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.

2
  • 1
    Filter the array first for empty elements. Commented Aug 17, 2016 at 2:48
  • @Dagon Yes there is :P I just had one in my mind with array_filter(), but not combined with implode(). Commented Aug 17, 2016 at 2:53

2 Answers 2

5

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);
   }
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

That will filter your array before imploding it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.