How do I make the final foreach instance end without the , character? As it stands every instance of $var2 is followed by a , character. Code to follow, thanks in advance.
foreach($tags as $var1 => $var2) {
if($_SESSION[$var1]!="off")
{
include($var2);
echo",";
//needs to include no , character on the last instance.
}
else
{
echo $var1;
}
}
First insert all your echo's into string. Then delete final instance of "," with preg_replace function:
$str = preg_replace('/\,$/', '', $str);
Another way is with a counter:
$len = count($tags);
$iter = 0;
foreach($tags as $var1 => $var2) {
if($_SESSION[$var1]!="off")
{
include($var2);
if($iter != $len-1)
echo",";
//needs to include no , character on the last instance.
}
else
{
echo $var1;
}
$iter++;
}
Another way with end() function
foreach($tags as $var1 => $var2) {
if($_SESSION[$var1]!="off")
{
include($var2);
if (end($tags) != $var2) {
echo",";
//needs to include no , character on the last instance.
}
else
{
echo $var1;
}
}
Using this you retrieve the last element with end()
and gets is key with key()
that you compare with the current key:
foreach($tags as $var1 => $var2) {
if($_SESSION[$var1]!="off")
{
include($var2);
//needs to include no , character on the last instance.
if(key(end($tags)) !== $var1)
{
echo",";
}
}
else
{
echo $var1;
}
}
Inside your foreach, change the echo ",";
to following:
if (end($tags) != $var2) {
echo ",";
}
Doing this will check if you are in the last index by comparing the current index to the last index of the $tags
array. Click here to see the PHP wiki on the end()
function.
This wil help you
$result = '';
foreach($tags as $var1 =>$var2) {
$result .= $var2.',';
}
$result = rtrim($result,',');
echo $result;
Try using the end()
function to get the last item:
$last_item = end(array_keys($tags));
foreach($tags as $var1 => $var2) {
if($_SESSION[$var1]!="off") {
{
include($var2);
if($var1 !== $last_key) {
echo",";
}
//needs to include no , character on the last instance.
}
else
{
echo $var1;
}
}
One way to check the last element and echo comma(,)
$numItems = count($tags );
$i = 0;
foreach($tags as $var1 =>$var2) {
if($_SESSION[$var1]!="off")
{
include($var2);
if(++$i != $numItems) {
echo ",";
}
}
else
{
echo $var1;
}
}