Storing array values in a single variable

Asked

Viewed 1,130 times

1

I could do so

$array = array(12, 14, 121, 123);
$var = $array[0].", ".$array[1].", ".......
echo $var

But how to do it if I don’t know the exact size of the array?

'Cause I’m getting her through a post that comes from a <select multiple="multiple"></select>

So you can’t tell the exact size of it.

  • 1

    Ever tried foreach?

  • Excuse me... But how? In the way I am thinking there is no way to keep all values.... But always the last inserted...

3 answers

3


  • Thanks! I didn’t know operator yet .= haha. But it worked perfectly here!

  • 1

    That one implode did in a row what my code did in almost 10 kkkk living and learning.

2

Another solution, formatting the way you suggested in the question, with comma:

$array = array(12, 14, 121, 123);
$newVar = "";
$arrayLength = count($array);
for($i = 0; $i < $arrayLength; $i++){
    if($i == ($arrayLength-1)){
        $newVar .= $array[$i];
    }else{
        $newVar .= $array[$i].",";
    }
}
echo $newVar;
  • To add the commas I did so, Diego : $var.=" , ". $item; And at the time of printing, I used substr() starting at 2

  • @Naldson what do you mean? I don’t understand.

  • 1

    http://ideone.com/undskA

  • 1

    @Very cool naldson, so you don’t need to mess with Dice from hehe array

  • 1

    @Naldson your code doesn’t make sense.

  • @bigown So it is... After I came to see that it is best to just use the "implode($array, ", ");"

Show 1 more comment

-4

So make it simpler:

$array = array(12, 14, 121, 123);

foreach ($array as $item) {


echo "<br>".$item;

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.