How to dynamically assign line break delimiter

Asked

Viewed 36 times

1

My question would be if there is any function that I can use in my example code below so that php itself is in charge of identifying that every two sets of values there is a line break without I have to put the delimiter & manually at the end of each line and I can get the same result I had in the example.

The set of values I need to adapt to this code comes separated only by comma:

 $str = "linha 1, linha 1, linha 2, linha 2, linha 3, linha 3";


 

My example code:

 $str = "
 linha 1, linha 1 &
 linha 2, linha 2 &
 linha 3, linha 3 &
 ";
 
 $arr= explode('&', $str); // transforma a string em array.
 
 $arrN = array();
 foreach($arr as $item){
     $valor = explode(',', $item); 
 
 echo $arrN[$valor[0]] = $valor[0] . $valor[1]. "<br>";    
     
 
   
 }

Upshot:

line 1 line 1

line 2 line 2

line 3 line 3

  • you have this string ordered and this pattern always? because you don’t even need to put a & for this!

  • values change, the order is always the same one row and two columns

1 answer

1


can be achieved with a for like this.

<?php
$str = "linha 1, linha 1, linha 2, linha 2, linha 3, linha 3";
 
$arr= explode(',', $str); // transforma a string em array.
 
for($i =0;$i< count($arr);$i = $i + 2){
    
 echo  $arr[$i] . $arr[$i+1]. "<br>";
}

can also add the comma to the string

<?php
$str = "linha 1, linha 1, linha 2, linha 2, linha 3, linha 3";
 
$arr= explode(',', $str); // transforma a string em array.
 
for($i =0;$i< count($arr);$i = $i + 2){
    
 echo  $arr[$i]. ",". $arr[$i+1]. "<br>";
}
  • I like your answer just one more thing.. if the values were: $str = "line 1, line 1 line 2, line 2 line 3, line 3"; there would be some way to treat this?

  • and need some reference to generate the array a good practice would be to use | to split the fields or in the example above with a , white space can be used in various locations generating undesirable return

Browser other questions tagged

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