irishwill200 irishwill200 - 3 months ago 7
PHP Question

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>

Answer

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

The reason you are seeing a single letter instead of an error:

  • 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

Comments