Reputation: 1094
I have array with some values after performing foreach loop I want to pass every value to a variable by comma separated, but last value should not come with comma(,).
<?php
$aa=array("id"=>1,"id"=>2,"id"=>3,"id"=>4);
$otherV = '';
foreach($aa as $key => $value){
if (!empty($otherV))
{
$otherV = $value.",";
}
else{
$otherV = $value;
}
}
echo $otherV;
?>
expected output I want output like this: 1,2,3,4
Upvotes: 1
Views: 971
Reputation: 1213
try this:
<?php
$aaray=array("a"=>1,"b"=>2,"c"=>3,"d"=>4);
$otherV = '';
$len = count($aaray);
$i=0;
foreach($aaray as $value){
$i++;
//check if this is not the last iteration of foreach
//then add the `,` after concatenation
if ($i != $len) {
$otherV .= $value.",";
}else{
//check if this is the last iteration of foreach
//then don't add the `,` after concatenation
$otherV .= $value;
}
}
echo $otherV;
?>
Upvotes: 4
Reputation: 797
You can not have the same position for each array value
$aa=array("a" => 1, "b" => 2, "c" =>3, "d" => 4);
foreach($aa as $value)
{
$temp[]=$value;
}
echo implode(",",$temp);
Upvotes: 0
Reputation: 94662
There are a number of mistakes in your code
<?php
// fix array creation, dont use `->` use `=>`
// and the keys cannot all be the same
$aa=array("a"=>1,"b"=>2,"c"=>3,"d"=>4);
$otherV = '';
foreach($aa as $key => $value){
//concatenate the value into otherV using .=
$otherV .= $value.",";
}
rtrim( $otherV, ','); // remove last comma
echo $otherV;
?>
Upvotes: 0