Forum Moderators: coopster

Message Too Old, No Replies

looping - remove character from last instance

         

ahmed24

4:38 pm on Jul 16, 2009 (gmt 0)

10+ Year Member



i am using the code below that echos the value

key1,key2,key3,

for($i=1; $i<=3; $i=$i+1)
{
echo "key".$i.",";
}

can anyone please tell me how i can remove the comma after key3 only?

thanks

andrewsmd

4:49 pm on Jul 16, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There are numerous ways. If it's always going to be key 3 then just do this
for($i=1; $i<=3; $i=$i+1)
{
if($i = 3){
echo "key".$i;
}//if
else{
echo "key".$i.",";
}//else
}

However that's not dynamic. If you had four keys then it would read
key1,key2,key3key4,
you could split them into an array to make them dynamic

this will be dynamic and remove the last comma no matter how many keys you give it
$arr = explode(",", "key1,key2,key3,key4,key5");

foreach($arr as $key => $i){

if($key != (count($arr) - 1)){
echo($i.",");
}//if
else{
echo($i);
}//else
}//foreach

ahmed24

4:53 pm on Jul 16, 2009 (gmt 0)

10+ Year Member



many thanks andrewsmd, you've been a great help. i will give that a try now.

Frank_Rizzo

6:47 pm on Jul 16, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Here's another option. Build a string, strip out the last character and then echo.

$string = '';
for($i=1; $i<=3; $i=$i+1)
{
$string .= "key".$i.",";
}

echo substr($string, 0, -1);

andrewsmd

7:05 pm on Jul 16, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Nice one Frank, now you should be able to build one or parse one ahmed.