2

I run a query and got id values in an array. Then I push those id like this array_push($id); then I implode ',' into an array and place it in a variable like this $val = implode(",",$id);. When I output it i get following result ,2,3,4,5,6,7,8. Problem in this result is that first value is ',' and it is because first record that I am getting from database is giving me Null value. I want to remove ',' from first place if first record is empty. So that desire result should be 2,3,4,5,6,7,8.

Please anybody can help me how can I remove ',' from first place. Or any suggestion to solve this problem

2
  • 2
    Perhaps, if you retrieve array from the db, you can put WHERE id IS NOT NULL in your SQL query. Commented May 10, 2013 at 14:06
  • 2
    There are several things you can do to "make the nulls go away", such as using array_filter as Baba mentions (btw, you must provide a custom callback to distinguish null from 0). But is making them go away the correct thing to do? That depends on your business rules. Commented May 10, 2013 at 14:07

1 Answer 1

1

Do it like this:

$id = array_filter($id, 'ord'); // removes 0 length values, or
$id = array_filter($id, 'strlen'); // same as above but a bit slower, or
$id = array_filter($id, 'count'); // removes only NULL values and empty arrays

$val = implode(",",$id);

You might also want to consider using is_numeric as the array_filter callback.

Doing just array_filter($id) will remove falsy (like 0) elements that you might want.

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

2 Comments

Note that is_numeric returns true for strings like '10e5' (because it could be scientific notation) which is often not what you want. ctype_digit is generally more appropriate, but will complain if its input is not a string.
@IMSoP: Yes, and is_int complains if it's not a integer. But I guess in this case everything is a string.

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.