I am attempting to produce a single string with 2 values dates and cost
If a user selects a start date of 1/1/2025 and an end date of 3/1/2025 and the cost is 250 I am looking to build a string as follows.
"20250101":250,"20250102":250
I am using the following code.
$pricepern = 250;
$period = new DatePeriod(
new DateTime($start_date),
new DateInterval('P1D'),
new DateTime($end_date));
foreach ($period as $key => $value) {
$individualdays = '"'.$value->format('Ymd').'":'.$pricepern.',';
echo $individualdays; // It works in here
}
echo $individualdays; // It only provides the last value out here
Would appreciate any help in understanding how I produce a single string outside of the for each. I did try implode outside however it indicated that the value was not an array.
Cheers
zero
2
Answers
To build a single string containing all the date-cost pairs, you can concatenate each
$individualdays
string inside the loop and then remove the trailing comma. Here’s a way you can do it:This code will produce the desired output string with all the date-cost pairs concatenated together, and the trailing comma removed.
Put all the
date:cost
pairs in an array and useimplode()
to combine them with comma delimiters.