0

I have an associative array in php. I am using a foreach loop and i want to create hyperlinks with the keys and values of my array like so: go to http://www.microsoft.com to visit microsoft.

The hyperlink is the value and microsoft is the key.

Here is my code:

$software=array("microsoft"=>"http://www.microsoft.com",....);

foreach ($software as $key=>$item){
    echo "Go to ".<a href=$item></a>"." to visit " ."<b>".$key."</b><br>";
}

What is wrong? Thank you

Jacob Tomlinson
  • 3,341
  • 2
  • 31
  • 62

4 Answers4

0
$software=array("microsoft"=>"http://www.microsoft.com",....);

foreach ($software as $key=>$item){

  echo "Go to <a href='".$item."'>to visit <b>".$key."</b></a><br>";
  // alternate
  // echo "Go to <a href='{$item}'>to visit <b>{$key}</b></a><br>";

}
jogesh_pi
  • 9,762
  • 4
  • 37
  • 65
  • Maybe because you use single quotes? Though they are allowed (http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.2) it is not common practise. – Christopher Will Mar 12 '14 at 09:19
0

You need to make sure that all your HTML is enclosed in quotes to make it a string. And then concatenate your variables in using the . operator.

$software=array("microsoft"=>"http://www.microsoft.com");

foreach ($software as $key=>$item){
    echo "Go to <a href=".$item.">".$item."</a> to visit <b>".$key."</b><br>";
}

Or you can include the variables in the string as long as you use double quotes and not single quotes. (Its a good idea to wrap the variable in curly braces to help the PHP parser know where the variable starts and stops).

$software=array("microsoft"=>"http://www.microsoft.com");

foreach ($software as $key=>$item){
    echo "Go to <a href={$item}>{$item}</a> to visit <b>{$key}</b><br>";
}
Jacob Tomlinson
  • 3,341
  • 2
  • 31
  • 62
0
  • You missed to quote the URL correctly
  • Your a-tag had no content
  • Your general quotation is invalid

So your code may look like this:

foreach ($software as $name => $url){
  echo 'Go to <a href="'.$url.'">'.$url.'</a> to visit <strong>'.$name.'</strong>';
}

And you probably do not want to use the b-tag, either use a styled span, or at least the strong-tag, see What's the difference between <b> and <strong>, <i> and <em>?

Community
  • 1
  • 1
Christopher Will
  • 2,991
  • 3
  • 29
  • 46
0

Please found your answer:

Replace the foreach loop with the below code

foreach ($software as $key=>$item){
   echo "Go to <a href=$item>$item</a> to visit <b>$key</b><br>";
}
Andolasoft Inc
  • 1,296
  • 1
  • 7
  • 16