I am creating a comma separated list using foreach and for. Below is the code…
$timeofdaylist = "";
foreach($_POST['timeofday'] as $key => $value)
{
if($timeofdaylist == "")
{
$timeofdaylist = "'".$value."'";
}
else
{
$timeofdaylist .= ",'".$value."'";
}
}
echo $timeofdaylist;
The above code gives me a comma separated list like this : ‘AM’,’PM’
Here my first condition $timeofdaylist == "" is working properly as I expected.
And now another piece of code
$timeofdaylist = "";
var_dump($timeofdaylist);
for($i=0;$i<count($_POST['timeofday']);$i++) {
if($timeofdaylist == "") {
$timeofdaylist = "'".$_POST['timeofday'][$i]."'";
} else {
$timeofdaylist = ",'".$_POST['timeofday'][$i]."'";
}
}
echo $timeofdaylist;
The above code only prints the last value, like this : ,’PM’
I have var_dumped timeofdaylist and checked before my first condition of $timeofdaylist == "". It shows length=0.
Can anyone distinguish the difference between above two pieces of code?
TIA
because you reset variable
$timeofdaylistin each iteration,so it only contains the last value of the array
Your first example,
$timeofdaylist .= ",'".$value."'";= concatenate the stringSo, I guess
Assuming typo is the cause of the problem …