SCor
SCor

Reputation: 17

Create comma separated list of links with variable in PHP

I have a variable which renders a list of usernames. Now, I need to add a link to each username. The link is built from a fixed URL and the username as a variable.

Example link: https://www.example.org/something?userid=$username

$usernames = $_POST['username'];
$username = '';
foreach($usernames as $value) {
$username .= "'" . $value . "', ";
}
$username = rtrim($username, ', ');

And then, I have the construction of the list:

<?php  $urls = explode(',', $usernameid);
$nritems = count ($urls); 
$positem = 0;
foreach($urls as $key => $usernameid)
{
echo "<a href="https://www.example.org/something?userid=' . $usernameid . 
'">'. $usernameid . '</a>";
if (++$positem != $nritems) { echo ", ";}
}?>

The variable is also used in other parts of the code, so I can't change it. The list is not displaying now.

Any help is appreciated.

Update: the form:

<form action="list.php" method="post" autocomplete="off">
  <div id="usrselect">
    <label>Select user <input type="text" name="username[]" id="userid" class="typeahead" required/></label>
   </div>
   <div class="button-section"> <input type="submit" name="List" /></div>
</form>

Upvotes: 0

Views: 474

Answers (2)

SCor
SCor

Reputation: 17

The working solution, for those who might face the same problem:

<?php $urls = explode(',', $usernameid);
$nritems = count ($urls); 
$positem = 0;
$displayuser = array("'", " ");
foreach($urls as $key => $usernameid)
{
echo '<a href="http://www.example.com/something?userId='.str_replace($displayuser, "", $usernameid).'">'.str_replace($displayuser, "", $usernameid).'</a>';
if (++$positem != $nritems) { echo ", ";}
}?>

Upvotes: 0

user8034901
user8034901

Reputation:

If you just want to get your quotes right:

echo '<a href="https://www.example.org/something?userid='.$usernameid.'">'.$usernameid.'</a>';

or

echo "<a href=\"https://www.example.org/something?userid={$usernameid}\">{$usernameid}</a>";

or

echo sprintf('<a href="https://www.example.org/something?userid=%d">%d</a>', $usernameid, $usernameid);

Upvotes: 1

Related Questions