Problem with concatenation of variable

2

I have a variable in a foreach that takes the id of the record:

$id_inscrito = $this->session->userdata('last_id');

I want to store this variable in another:

$ids_ = $id_inscrito.'|'.$id_inscrito;

Give me the result in id1|id2|id3 format.

How can I do this?

    
asked by anonymous 04.02.2015 / 22:15

3 answers

2

Within your foreach , collect in an array all the IDs, and in the output of foreach execute the implode() function of PHP to transform into a string with the interspersed separator you need:

$ids = array();

foreach(????) {
    $ids[] = $this->session->userdata('last_id');
}
echo implode('|', $ids);
    
17.09.2015 / 20:01
1

Read PHP's implode function.

If in the variable $this->session->userdata('last_id') returns an array with the ids you want, just do:

$ids = implode('|', $this->session->userdata('last_id'));

And when I echo the variable ids will return exactly what you wanted. Hope this helps! ;)

    
04.02.2015 / 22:31
1

You can concatenate the string as @rray put in the comments:

$ids_ .= $id_inscrito .'|';

Remembering that you must initialize the $ids_ variable before the loop. Another point to consider is that the last id will always be followed by a | character. A more complete solution would look like this:

$ids_ = '';
foreach (...) {
    // codigo

    // se o $ids_ não estiver vazio adiciona '|' antes do próximo id
    $ids_ .= ($ids_ == '') ? $id_inscrito : '|' . $id_inscrito ;
}

Another possible way is to use arrays, as @HaroldoTorres put in your answer:

$ids_ = array();
foreach (...) {
    // codigo

    $ids_[] = $id_inscrito;
}
$ids_ = implode('|', $ids_);
    
05.02.2015 / 12:33