Search code examples
phphtmlanchorhref

First anchor links to #


I have an array that looks like this:

$anchors = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z', 'Å', 'Ä', 'Ö', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '"');

I then link each letter to its anchor:

foreach ($anchors as $anchor){
echo '<h2 style="display:inline; margin-left:25px; margin-bottom:15px;"> <a href="#' . $anchor . '">' . $anchor . ' ' . '</h2>';
}
echo '<div style="margin-top:100px;"></div>';

foreach ($anchors as $anchor2){
echo '<h3 id="' . $anchor2 . '">' . $anchor2 . '</h3>';

Then further code follows, I get the anchors to display and work as intended EXCEPT for the first ancho 'A' links to #.

so what i get is pretty much this:

A B C

A <- this links to # (Against my wish)

Apples

Attack

B <-- this does not link (just as I want it to behave)

Bananas

Brothers

C <-- this does not link (just as I want it to behave)

Cinnamon

I cant see how the 'A' Gets linked to #. When i click it it moves to the top of the page.


Solution

  • Try close your <a> tag. Try this.

    foreach ($anchors as $anchor){
    echo '<h2 style="display:inline; margin-left:25px; margin-bottom:15px;">
    <a   href="#' . $anchor . '">' . $anchor . ' ' . '</a></h2>';
    }
    echo '<div style="margin-top:100px;"></div>';
    
    foreach ($anchors as $anchor2){
    echo '<h3 id="' . $anchor2 . '">' . $anchor2 . '</h3>';