Search code examples
javascriptphpjqueryexplodeimplode

explode/implode array in PHP


Not sure why I am having this problem. I have used this same code on a previous project with no problems.

I'm generating an array using checkboxes in JavaScript. I can successfully $.post the array to PHP, but I keep receiving the following error:

Warning: explode() expects parameter 2 to be string, array given in D:\htdocs\deliverynoticeV2\process\updateRecord.php on line 14

Warning: implode(): Invalid arguments passed in D:\htdocs\deliverynoticeV2\process\updateRecord.php on line 15

It repeats the same error about 4 times, as I have 4 different arrays I'm sending over.

Starting with the JavaScript:

$('#updateRecords').on('click', function(e)
{ 
  e.preventDefault();
  $('#updateForm input').val('');

  var checkcontainer = [];
  var checkorder = [];
  var checktrucker = [];
  var checkconsignee = [];

  $(".checkEdit:checked").each(function(){
    checkcontainer.push($(this).data("checkcontainer"));
    checkorder.push($(this).data("checkorder"));
    checktrucker.push($(this).data("checktrucker")); 
    checkconsignee.push($(this).data("checkconsignee")); 
  });

  console.log(checkcontainer);

  $.post('process/updateRecord.php', {checkcontainer:checkcontainer,
  checkorder:checkorder, checktrucker:checktrucker, checkconsignee:checkconsignee}, 
  function(data)
  {
    console.log(data);
  }); 
});

When I console out the variable 'checkcontainer', I see the following:

["FSCU7122545", "TGHU6235458", "TCNU6900047"]

Over in PHP, the code looks like this:

<?php
if(isset($_POST['checkcontainer']))
{
  $checkcontainer = $_POST['checkcontainer'];
  $checkorder = $_POST['checkorder'];
  $checktrucker = $_POST['checktrucker'];
  $checkconsignee = $_POST['checkconsignee'];

  $containerSplit = explode(",", $checkcontainer);
  $containers = "'" . implode("', '", $containerSplit) . "'";
  $orderSplit = explode(",", $checkorder);
  $orders = "'" . implode("', '", $orderSplit) . "'";
  $truckerSplit = explode(",", $checktrucker);
  $truckers = "'" . implode("', '", $truckerSplit) . "'";      
  $consigneeSplit = explode(",", $checkconsignee);
  $consignees = "'" . implode("', '", $consigneeSplit) . "'";

  echo $containers;
}
?>

As stated, I've used this same code in a previous project. Why am I receiving the above error?


Solution

  • You actually don't need the explode() calls before your implode() ones because the data you send are arrays (Your variables in your js are arrays). So all your $_POST variables are arrays.