2

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!

2
  • 1
    This works. You just have to remove the trailing comma when you are done. Use rtrim() for that. Commented Apr 14, 2019 at 18:09
  • array_filter and join are your friends… Commented Apr 14, 2019 at 18:19

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.