Let's say I have a php array called $t
with 5 elements in it. For demonstration purposes, let's call it $t = [a,b,c,d,e]
.
I want to echo all elements in parenthesis like this:
(a, b, c, d, e)
. However, I want this parenthesis format to hold if there are null values in the array $t
.
For example, if c
and d
are null in the array, it should echo (a, b, e)
. What's an efficient way of doing this without trying every possible permutation (impossible with large array sizes).
I have tried:
echo "("
for($j=0; $j<5; $j++){
if(!empty($t[j])){
echo " $t[j], ";
}
}
echo ")"
But this leaves a comma at the end, and even then I'm not sure if it accounts for every possible case. Thanks in advance!
This works pretty well:
<?php
function is_not_null($v) { return !is_null($v); }
$t = ['a', 'b', null, null, 'e'];
echo '('.implode(',', array_filter($t, 'is_not_null')).')';
Result:
(a,b,e)