skip to Main Content

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


  1. 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:

    $start_date = '2025-01-01';
    $end_date = '2025-03-01';
    $pricepern = 250;
        
    $period = new DatePeriod(
        new DateTime($start_date),
        new DateInterval('P1D'),
        new DateTime($end_date)
    );
    
    $fullString = ''; // Initialize an empty string to hold the full result
    
    foreach ($period as $key => $value) {
        $individualdays = '"' . $value->format('Ymd') . '":' . $pricepern . ',';
        $fullString .= $individualdays; // Concatenate each day string
    }
    
    // Remove the trailing comma
    $fullString = rtrim($fullString, ',');
    
    echo $fullString;
    

    This code will produce the desired output string with all the date-cost pairs concatenated together, and the trailing comma removed.

    Login or Signup to reply.
  2. Put all the date:cost pairs in an array and use implode() to combine them with comma delimiters.

    $days_array = array_map(fn($value) => '"'.$value->format('Ymd').'":'.$pricepern, $period);
    $individual_days = implode(',', $days_array);
    
    echo $individual_days;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search