Avoid the last occurrence of a concatenated character in a loop

5

The question is whether I have a foreach or any other repeat structure that receives data from the table and displays the categories:

foreach ($categories as $c){
            $c.nome . ' - ';
    }

Assuming this code would display as a result:

Categoria_1 - Categoria_2 - Categoria_3 -

How do you make sure that this "-" does not appear after the last loop, how do you hide it?

My intention is that instead of displaying as shown above the end result is:

Categoria_1 - Categoria_2 - Categoria_3

with "-" appearing neither at the beginning nor at the end, but only in the category names.

    
asked by anonymous 26.02.2015 / 01:27

3 answers

6

Use the implode function:

$categorias = array("Categoria 1","Categoria 2", "Categoria 3");
$lista = implode(" - ", $categorias);

Update :

For objects I used array_map to return only the nome property:

$nomes = array_map(function($objeto) { return $objeto->nome; }, $categorias);
$lista = implode(" - ", $nomes);

See example working on ideone

    
26.02.2015 / 01:43
4

For this you can shorten the final string using

$string = substr($string, 0, -3); // aqui digo para retirar os ultimos 3 caracteres
// ou 
$string = rtrim($string, ' - ');  // aqui digo para retirar a string " - " da string inicial

Notice that in your loop you are not concatenating correctly, you must have

$string.= $c -> nome.' - ';

What is missing is the variable $string , the concatenation operator .= and the way you access the object property that should be -> and not . .

    
26.02.2015 / 01:31
3

You can do this

foreach ($c as $categories){
          $categoria.= $c.nome.' - ';
    }
$string = strlen($categoria);

$categories = substr($categoria,0, $string-1);

Test and say something

    
26.02.2015 / 01:32