4

I would like to know how to make a list of links appear on my page displaying a name but when you click it, it navigates to the link.

I currently know how to make a list and display the items of it using the foreach command and arrays but is there a way I can make it so I have an array, containing an array, containing the name of the link and the link itself, like so:

$links = array(array("Google","//google.co.uk"),array("Bing","//bing.co.uk"))
foreach ($links as $myurl){
foreach ($myurl as $url){
echo "<a href='".$url."'>".$myurl."</a>";
}};

I know the above doesn't work but if anyone can help with this problem, it is much appreciated.

celliott1997
  • 1,115
  • 1
  • 8
  • 17

2 Answers2

8
$links = array('Google' => 'www.google.com', 'Yahoo' => 'www.yahoo.com');

foreach($links as $k => $v) {
  echo '<a href="//' . $k . '">' . $v . '</a>'; 
}

As you can see I don't specify http or https, just // works on both! See: http://google-styleguide.googlecode.com/svn/trunk/htmlcssguide.xml

You can add links to $links with:

$links['stackoverflow'] = 'www.stackoverflow.com';
Wouter Dorgelo
  • 11,770
  • 11
  • 62
  • 80
  • You should explain that what he needed was an "associative array" rather than the 2-dimensional array he was trying to use. He was getting lost in his dimensions. :) – Ed Manet Jul 02 '12 at 20:29
  • Hi Ed, yes.. I added `$links['stackoverflow'] = 'www.stackoverflow.com';` so he can see how `$links` can be populated :) – Wouter Dorgelo Jul 02 '12 at 20:31
2
$links = array(
array("Google","//google.co.uk"),
array("Bing","//bing.co.uk")
);

foreach ($links as $urlitem){ 
echo "<a href='".$urlitem[1]."'>".$urlitem[0]."</a>";
}
Roger Wayne
  • 419
  • 3
  • 20
  • Creating an extra dimension is unnecessary while `Google` IS the keyvalue of value `www.google.com` – Wouter Dorgelo Jul 02 '12 at 20:33
  • It is reasonable to adapt the answer to suit the OP's sample data. This answer, though, is missing its educational explanation and standard code tabbing. – mickmackusa Jul 27 '22 at 05:16