i am trying to concatenate values into a string which later is attached to a hidden input.
This is the forach loop:
<?php
$langid = array();
$transLang = '';
foreach($translator['langs'] as $lang) {
$curlang = $lang->term_id;
$langid[] = $curlang;
$transLang .= '('.$curlang.'), ';
// for testing
echo $transLang."<br />";
}
?>
<input type="hidden" name="selectedLang" value="<?php echo $transLang; ?>" />
.
The langid[] array grabs everything correctly
but $transLang echoed into the input only shows the first value which is: (3),
When i use this line:
echo $transLang."<br />";
Which i added for testing it echoes:
(3),
(3), (10),
(3), (10), (12),
(3), (10), (12), (27),
(3), (10), (12), (27), (19),
(3), (10), (12), (27), (19), (20),
The last one is the complete string after the foreach finished runing but the input field value is always only the first run meaning (3),
Any idea why this is happening?
I tried to run a dummy test. Here is my code
<?php
$a = "";
$loop = array("1","2","3","4","5","6","7","8","9");
foreach($loop as $i){
$a .= "($i),";
}
?>
<input type="hidden" name="selectedLang" value="<?php echo $a; ?>" />
and i get the following output
<input type="hidden" name="selectedLang" value="(1),(2),(3),(4),(5),(6),(7),(8),(9),">
OR You ca use an additional array
to store these strings
and echo
the last index
So Your code will changed to this one
<?php
$langid = array();
$strings = array();
$transLang = '';
foreach($translator['langs'] as $lang) {
$curlang = $lang->term_id;
$langid[] = $curlang;
$transLang .= '('.$curlang.'), ';
$strings[] = $transLang;
// for testing
//echo $transLang."<br />";
}
?>
<input type="hidden" name="selectedLang" value="<?php echo end($strings); ?>" />
Both methods I've tested on my dummy values and it's working fine for me. Try to use second method first.
You can use array implode for that: http://php.net/manual/en/function.implode.php