1

I have two comma delimited lists corresponding to the Ids and values of something returned by a query. I can easily convert each into an array using explode.

My question is how can I convert the two lists into a set of hyperlinks that use one from each as follows:

Ids:  34,23,78
Values: red, blue, green

Links: <a href='get.php?id=34'>red</a> etc.

I can use:

$valuesarray =explode(',',$values);
foreach($valuesarray as $val) {
Echo ....$Val
}

But how do I get the Ids into the link?

6 Answers 6

2

Personally, I'd use array_combine to combine them into one array:

$arr = array_combine(explode(",",$ids),explode(",",$values));
foreach($arr as $id=>$value) {
    ...
}

But there are other ways. Such as:

$idarray = explode(",",$ids); $valuesarray = explode(",",$values);
// option 1:
foreach($idarray as $k=>$id) {
    $value = $valuesarray[$k];
}
// option 2:
$length = count($idarray);
for( $i=0; $i<$l; $i++) {
    $id = $idsarray[$i]; $value = $valuesarray[$i];
}

And so on.

Sign up to request clarification or add additional context in comments.

Comments

1

using $key => $value in the for each loop will accomplish this.

foreach($valuesarray as $id => $val) {
echo '<a href="file.php?id=' . $id . '">' . $val . '</a>';
}

1 Comment

That will work if you use array_combine to make the id array the keys and the other the values.
1

If you can assume the count of items is always the same you can just do a regular for loop:

for ($i = 0; $i < count($valuesarray); $i++) {
    echo "<a href='get.php?id=" . $idsarray[$i] . "'>" . $valuesarray[$i] . "</a>";
}

Comments

0

You could map them into an array with "id's" as key and "values" as values, like this:

$id_array = explode(',', $ids);
$value_array = explode(',', $values);
$final_array = array();

for ($i=0; $i < count($id_array); $i++) {
    $final_array[$id_array[$i]] = $value_array[$i];
}

Note that you may also want to verify that the number of id's matches the number of values before entering the loop.

1 Comment

array_combine will do this for you.
0
$ids = '33,22,55';
$values = 'red,yellow,blue';

$ids = explode(',', $ids);
$values = explode(',', $values);

foreach($ids as $key => $value){
    echo "<a href='get.php?id=$ids[$key]'>$values[$key]</a><br />";
}

Comments

0

Try this:

$id_arr = explode(',',$ids);
$val_arr = explode(',',$values);
for($i = 0; $i < count($id_arr); $i++)
{
    echo '<a href="get.php?id='.$id_arr[$i].'">'.$val_arr[$i].'</a>';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.