Problem with variable concatenation

Asked

Viewed 192 times

2

I have a variable in a foreach that picks up the registration id:

$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 the format id1|id2|id3.

How can I do that?

  • 2

    Use the operator .= to concatenate strings.

  • 1

    Like the for each will vary? What changes from one element to the other? Where does its data source come from?

  • 1

    Edit the question and add the code where the foreach is

3 answers

2


Within your foreach, collect in an array, all Ids, and at the exit of the foreach perform the function implode() PHP to transform into a string with interleaves of the separator you need:

$ids = array();

foreach(????) {
    $ids[] = $this->session->userdata('last_id');
}
echo implode('|', $ids);

1

Give a read on the function implode of PHP.

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 you echo the variable ids will return exactly what you wanted. I hope to have helped! ;)

  • 2

    It does not seem to be the case to return a array, at least it would be strange such a method to return it.

1

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

$ids_ .= $id_inscrito .'|';

Remembering that you should initialize the variable $ids_ before the loop. Another point to consider is that the last id will always be followed by a character |. A more complete solution would be 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 their answer:

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

    $ids_[] = $id_inscrito;
}
$ids_ = implode('|', $ids_);
  • It doesn’t seem strange that this $id_inscribednão varie? Eu acho que a pergunta não está bem feita e as respostas estão especulando soluções. Pode até ser que acertem mas sem o AP confirmar este é um código esquisito. Vai ficar algo assim:1|1|1|1|1`. It does not seem likely that he wants this.

  • @Bigown AP said it runs this line inside the foreach: $id_inscrito = $this->session->userdata('last_id');. So I guess the $id_inscrito varie yes. He didn’t put anything stating that he has a problem with the variable. The problem with his code is that the variable $ids_ is being overwritten every time.

  • You may be right, I’m just not sure.

  • 1

    at the base of the achometer, I think last_id comes from an entry in the database.. must have a loop inserting new records in the database and in the same loop is taking advantage to take the ids and mount them in a single string.

Browser other questions tagged

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