Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

implode

I am trying to get the following output:

string1, string2, string3

Those values comes from $var1, $var2 and $var3 but they can be NULL 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 NULL 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?

like image 781
ReynierPM Avatar asked Sep 01 '25 22:09

ReynierPM


1 Answers

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 : '-';
like image 81
AbraCadaver Avatar answered Sep 03 '25 15:09

AbraCadaver