Thursday 30 August 2018

The PHP join adds a comma before the first value

I am using a join statement in PHP and it's adding a comma before the first value. I'm not sure why.

Here is the code
$columns = join(', ', $column_names). ' ';

Here is the result
,value1, value2, value3

It's sent using AJAX, and here's how the array is created on the front end using jQuery.
$('#preview_button').click(function() {
    var rc_column_names = ['not', 'set'];
    if($('#rc_custom_columns').is(':checked')) {
        rc_column_names = [];
        $(".list2 li").each(function() {
            rc_column_names.push($(this).text());
         });
    }

    $.ajax({
        url:'core/functions/create_report_preview.php',
    type: 'post',
    data: { 'rc_column_names': rc_column_names }
    }).fail (function(data) {
        //code
    }).done(function(data) {
        //code
    });
});

So again, the question is. Where is this comma coming from? Why is it added before the first value?

You probably have an empty value as your first array element. Use array_filter()before calling join() to remove empty values from your array.

0 comments:

Post a Comment