I am trying to add a line break after two elements in an array, however I am not able to get the line break in the correct position. I think this is an error with my PHP code below:
PHP:
$serviceinfo = implode("",array_map(function($i){
return implode("<br>",$i);
},array_chunk($_POST['servicelist'],2)));
$serviceinfo outputs the values in the following format:
Value1
Value2Value3
Value4Value5
Value6
I need it to output the values like this:
Value1 Value2
Value3 Value4
Value5 Value6
I am including my jQuery below in case this is causing any issues with the formating:
jQuery:
let values = [];
$("label[for='servicelist-label[]'], input[name='servicelist-details[]']").each(function() {
values.push($(this).text());
values.push($(this).val());
});
Any help would be much appreciated! Thank you.
CodePudding user response:
You are so close, you just need to switch the implode-separators:
$serviceinfo = implode("<br>",array_map(function($i){
return implode(" ",$i);
},array_chunk($_POST['servicelist'],2)));
This should result in the desired output.
CodePudding user response:
@clash was on the right track with the fact I needed to switch the implode separators. In the end my array_chunk needed to have the value of 4 and the line breaks needed to be in different locations in order for it to work. Here is the working code for anyone else with a similar problem:
$serviceinfo = implode(array_map(function($i){
return implode(" ", $i);
},array_chunk($_POST['servicelist'],4)),"<br>");
EDIT: As pointed out by @clash, my implode code will not work in PHP8. It looks like my array is incorrect. Basically I am trying to include both the label AND checkbox value in the array, however all of the labels are being added regardless of whether the checkbox is checked or not.
This is a jQuery problem I do not know how to solve. The code used is below:
PHP Form Elements:
<label for="servicelistlabel[]" >Service 1: </label><input type="checkbox" name="servicelistcheckbox[]" id="servicelist1" value="Service1"><br>
<label for="servicelistlabel[]" >Service 2: </label><input type="checkbox" name="servicelistcheckbox[]" id="servicelist2" value="Service2"><br>
<label for="servicelistlabel[]" >Service 3: </label><input type="checkbox" name="servicelistcheckbox[]" id="servicelist3" value="Service3"><br>
jQuery:
let values = [];
$("label[for='servicelistlabel[]'], input[name='servicelistcheckbox[]']:checked").each(function() {
values.push($(this).text());
values.push($(this).val());
});
PHP Implode Function (incorrect):
$serviceinfo = implode(array_map(function($i){
return implode(" ", $i);
},array_chunk($_POST['servicelist'],4)),"<br><br>");