Answer
Use implode()
<?php
$alldays = array('2','3','4');
$string = implode(',', $alldays);
echo $string;
Try it online!
Debug
Let's walk though the code
<?php
// Define alldays
$alldays = array('2','3','4');
// For each day
foreach($alldays as $day) {
// Create(=) a string, add $day and a comma
$string = $day.',';
// Remove the last char from $string and save ('NOT ADD') in $string_without_last_comma
$string_without_last_comma = substr($string, 0, -1);
// Show string
echo $string;
// Show string with last char
echo $string_without_last_comma;
}
// String here is the last char?
echo $string;
So the loop does show all those values, but they're not being added to eachother, only shown once per loop iteration.
Recap;
- Since you're doing
$string = $day.',';
you're overriding $string
every loop
- Same for
$string_without_last_comma
; you're not appending anything, only overriding
implode()
would give the desired result
Fixed original code
Note: Pure for learning purposes, I'll still recommend implode()
.
Without the use of implode()
, my guess is that you're trying to do something like this;
<?php
// Define alldays
$alldays = array('2','3','4');
// Create empty string
$string = '';
// For each day
foreach($alldays as $day) {
// Add(.=) $day and a comma
$string .= $day . ',';
// Keep doing this logic for all the $day's in $alldays
}
// Now $string contains 2,3,4,
// So here we can create $string_without_last_comma by removing the last char
$string_without_last_comma = substr($string, 0, -1);
// Show result
echo $string_without_last_comma;
Here we
- Create an empty string
- Loop through all the days
- Add (
.=
) day to $string
and add a comma
- After the loop, we can remove the last comma
- Show the result
Try it online!