Alko Alko - 3 months ago 15
PHP Question

Php implode empty array

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.

Answer

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

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

That will filter your array before imploding it.