1

I'm trying to create a drop down box that is populated by an array. When I view my code the browser just displays pieces of the php code.

Here is what the browser displays:

'; foreach ($array as $value) { $html .= '
$value
'; } $html .= ''; return $html; } ?> 

Here is my code:

<html>
<head>
<title>test</title>
<?php

$cities = array( 'San Francisco', 'San Diego', 'Los Angeles');

function createDropDown($name, $array) {

  $html = '<select name=$name>';

  foreach ($array as $value) {
    $html .= '<option value="$value">$value</option>';
  }
  $html .= '</select>';
  return $html;
}
?>
</head>
<body>
<form>

<?php
createDropDown("cities", $cities);
?>

</form>
</body>
</html>
2
  • 3
    You sure your server supports PHP? Commented Jul 15, 2011 at 19:49
  • 1
    Future reference: you can only embed variables in strings if you use double quotes. Otherwise, you'll need to concatenate like @AlienWebguy did below. Commented Jul 15, 2011 at 19:54

4 Answers 4

2

You need to echo your output as well. You build the string but never output.

<html>
<head>
<title>test</title>
<?php

$cities = array( 'San Francisco', 'San Diego', 'Los Angeles');

function createDropDown($name, $array) {

  $html = '<select name="' . $name . '">';

  foreach ($array as $value) {
    $html .= '<option value="' . $value . '">' . $value . '</option>';
  }
  $html .= '</select>';
  return $html;
}
?>
</head>
<body>
<form>

<?php
echo createDropDown("cities", $cities);
?>

</form>
</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

1

Most likely your server isn't configured to treat .php files as PHP scripts, and is serving them up as html/plaintext. If you view-source the page this is happening on, you'll probably get the full PHP source code. The <?php is seen as an opening HTML tag, which isn't closed until just before the foreach loop, so all the intermediate text/code is "hidden" in HTML view.

Comments

1

Change

$html = '<select name=$name>';

to

$html = '<select name="' . $name. '">';

Change

$html .= '<option value="$value">$value</option>';

to

$html .= '<option value="' . $value . '">' . $value. '</option>';

Comments

0

' doesn't parse, but " does.

 $html = "<select name=$name>";

will do it.

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.