ReynierPM ReynierPM - 1 year ago 51
PHP Question

Implode values from array with NULL or empty values cause unexpected output

I am trying to get the following output:

string1, string2, string3

Those values comes from
but they can be
at some point and here is where my problem is.

So far this is what I have:

$arr = array(
$var1 !== null ? $var1 : '',
$var2 !== null ? $var2 : '',
$var3 !== null ? $var3 : '',

echo $arr !== '' ? implode(', ', $arr) : '-';

This are the test I've run:

input: array('string1', 'string2', 'string3')
output: string1, string2, string3

input: array('string1', 'string2')
output: string1, string2

input: array('', '', '')
output: , ,

input: array(null, null, null)
output: , ,

As you may notice if values are coming everything work as I want, if values are coming
then I am getting
, ,
when I what I want is just a

I have tried to find whether the array contains empty values or not using this code:

$cnt = count($arr) !== count(array_filter($arr, "strlen"));
echo $cnt;

Then I've run the following test:

input: array('string1', 'string2', 'string3')
output: 3

input: array('string1', 'string2')
output: 2

input: array('', '', '')
output: 1

input: array(null, null, null)
output: 1

What I am missing or doing wrong here? How I can achieve this?

Answer Source

Filter the array before implode and if the imploded array is an empty string assign -, otherwise assign the imploded array:

$result = implode(', ', array_filter($arr)) ?: '-';

For PHP < 5.3.0 not supporting ?: then:

$result = ($s = implode(', ', array_filter($arr))) ? $s : '-';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download