William
William

Reputation: 1069

PHP displaying first letter of array in dropdown?

My issue is that the dropdown is actually populating correctly but with only the first letter of that particular line.

I have the following in my file:

Monday

Tuesday

Wed

It is displaying as:

M

T

W

Any ideas?

My code:

<select id="playlist_wrongstyle" class="form-control"  style="visibility:visible; width:250px;">
<option selected="selected">Choose one</option>
<?php
  $returnedScheduleNamesArray = explode ("\n", file_get_contents('/srv/http/schedulenames'));

  array_pop($returnedScheduleNamesArray); //remove empty last line

  foreach($returnedScheduleNamesArray as $name) 
  {
?>
      <option value="<?=$name['name']?>"><?=$name['name']?></option>
<?php
  }
?>
</select> 

Upvotes: 1

Views: 584

Answers (3)

Stephen
Stephen

Reputation: 18964

$name is a string. You should just echo name: <?= $name >

The reason you are seeing a single letter:

  • String characters can be accessed using array bracket syntax:

    $name = 'Monday';
    $name[0] === 'M'; // true
    
  • PHP is coercing your string 'name' into an integer, and this evaluates to 0:

    (int)'name' === 0; // true
    
  • So, $name['any string'] === $name[0]; // true

Upvotes: 5

Duane Lortie
Duane Lortie

Reputation: 1260

Ooops, you've found the PHP magic trick. PRESTO! Strings are arrays!

         $name ='Bob';// thats a string
         echo $name['0']; // prints B, like an array
         echo $name['1']; // prints o, like an array

Strings variables are actually arrays, but in your case, you don't want that.. so

<option value="<?=$name?>"><?=$name?></option>

Upvotes: 3

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

This is basically what's happening with $name['name']:

foreach (['Monday', 'Tuesday'] as $name) {
    echo $name['nonexistent'];
}

If you adjust your error reporting level, you'll see

Warning: Illegal string offset 'nonexistent'

When PHP sees you use ['something'] after a string, it thinks you're trying to access a specific character within it (which you can do, but only with numeric indexes). But, since PHP expects an integer there, when you reference an illegal string offset, it gets converted to an integer, so you'll probably get index zero, the first letter, unless your illegal string offset starts with something that will convert to nonzero. (e.g. $day['3illegal'] gets you "d" and "s".)

Upvotes: 4

Related Questions