How do you put two variables together?

Asked

Viewed 84 times

0

I have two variables like this

$links = "link1
link2
link3
link4";

$titulo = "titulo1
titulo2
titulo3
titulo4";

Can someone help me put the two together and stay that way:

<a href="link1">Titulo1</a>
<a href="link2">Titulo2</a>
<a href="link3">Titulo3</a>
<a href="link4">Titulo4</a>

1 answer

4


Break the two variables in array by line breaking \n and iterate on one by taking the value of the other by the index:

<?php
$links = "link1
link2
link3
link4";

$titulo = "titulo1
titulo2
titulo3
titulo4";

$links_array = explode("\n", $links);
$titulo_array = explode("\n", $titulo);

foreach($links_array as $indice=>$link){
   echo '<a href="'. $link .'">'. $titulo_array[$indice] .'</a>';
}
?>  

The result will be HTML:

inserir a descrição da imagem aqui

  • with this function, if in $links there is a blank space below the last value Link4, there is a <a href></a> blank in echo, it is possible to remove and avoid this with this function?

  • Vc can remove the last line break with preg_replace: $links_array = explode("\n", preg_replace('/\n$/', '', $links));

  • thanks, it worked... but you know if for example you have a space between link1 and Link2, you will have a <a href></a> between them, you know if you had spaces between links?

Browser other questions tagged

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