1

THE ANSWER THAT WORKED FOR ME BASED ON AN ANSWER GIVEN

while($post = mysql_fetch_array($tags)) {
        $push = explode(',', $post['tags']);
        $array = array_merge($array, $push);
}

So I'm trying to display tags from my data base and make links out of them like this:

<?
$tags = mysql_query( 'SELECT tags  FROM `Table`');
$array = array();
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
array_push($array, $push);
}
foreach ($array as $value) {?>
    <a href="url.php?tags=<? echo $value?>"><? echo $value?></a>
<? }
?>

However all I get back is

    <a href="url.php?tags=Array">Array</a>

Where I should be having at least three lines as was previously produced by

<?
$tags = mysql_query( 'SELECT tags  FROM `Table`');
while($post = mysql_fetch_array($tags)) {
$array = explode(',', $post['tags']);
foreach ($array as $value) {?>
<a href="url.php?tags=<? echo $value?>"><? echo $value?></a>
<? }
}
?>

The code being called looks like this:

tag1, tag2, tag3

Tried

while($post = mysql_fetch_array($tags)) {
    $push = explode(',', $post['tags']);
array_merge($array, $push);
}
foreach ($array as $value) {?>
<a href="index.php?tags=<? echo $value?>"><? echo $value?></a>

now foreach doesn't return a value

4
  • Just to point this out: try to use <?php ?> syntax Commented Jun 12, 2012 at 23:03
  • why did you explode $post[tags]? Commented Jun 12, 2012 at 23:09
  • @tunmisefasipe probably because they're stored in the database as a comma-separated string. Commented Jun 12, 2012 at 23:12
  • I guessed so.Made it confusing Commented Jun 12, 2012 at 23:14

1 Answer 1

3

Use array_merge(), because array_push() will push the output of explode(), which is an array, as a whole to the array in the first argument, creating a jagged array.

As for your edit, this works:

$array = array_merge($array, $push);

foreach ($array as $value)
{
    echo '<a href="url.php?tags=' . $value . '">' . $value . '</a>';
}

Please note that array_merge() (contrary to array_push(), gotta love the consistency) does not alter the array passed as its first argument, so you'll have to store the return value which I do on the first line ($array = ...).

While outputting to HTML, you also might want to put a $value = htmlentities(trim($value)); in the foreach loop.

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

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.