Saving values from an array to a single variable

1

I could do so

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

But how do I do if I do not know the exact size of the array ?

Because I'm getting it through a post that comes from a <select multiple="multiple"></select>

So you can not tell the exact size of it.

    
asked by anonymous 08.11.2015 / 01:14

2 answers

3

This is probably what you want:

$array = array(12, 14, 121, 123);
$var = "";
foreach ($array as $item) {
    $var .= $item . " ";
}
echo $var;

See running on ideone .

Manual of foreach .

Compound Assignment Operator's Manual .

This way you scan all the elements. There are several other ways to achieve the same effect, but this is the most appropriate.

In this specific case you can do something simpler:

implode($array, ", ");
    
08.11.2015 / 01:19
2

Another solution, formatting the way you suggested in the question, 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;
    
08.11.2015 / 01:30