Purple Lady
Purple Lady

Reputation: 491

Foreach Loop Only Displaying One Value From Array

I have tried researching other questions similar to my problem, but I haven't found anything that addresses this specifically. I am selecting data using mysqli and displaying it in a table. The column table_yard can have multiple values, so I exploded those values and stored them as an array to be looped through and then stored the result in variable $yard_name. I later assign this variable to a row in my table like so ($get is storing the sql query):

 while ($row = mysqli_fetch_assoc($get)) {
    $yards = explode(",", $row[table_yard]);
foreach ($yards as $yard) {
    $yard_name = $yard . ", ";
}
    $table_rows .= "<tr>
                <td>" . mdy($row[table_date]) . "</td>
                <td>" . $yard_name . "</td>
                </tr>";

The problem is, if there is more than one value in that array, it only displays the first item. I ran a debug on $yards to see if it was even getting all the values of the array, and it is, as shown here:

Array (
[0] => 711
[1] => 2793
[2] => 988
)

Although, this is what gets displayed in the <td> cell:

711, 

What I want it to display is this:

711, 2793, 988 

I am sure it's a rookie mistake, but I can't figure it out. Thank you in advance for any help.

Upvotes: 0

Views: 3502

Answers (1)

Bankzilla
Bankzilla

Reputation: 2096

Untested but this should help fix the issue. Defining $yard_name before the loop so it doesn't get constantly overwritten

while ($row = mysqli_fetch_assoc($get)) {
    $yards = explode(",", $row[table_yard]);
    $yard_name = "";
    foreach ($yards as $yard) {
        $yard_name .= $yard . ", "; // Add to the string instead of overwriting
    }
    $table_rows .= "<tr>
        <td>" . mdy($row[table_date]) . "</td>
        <td>" . trim($yard_name, ",") . "</td>
    </tr>";
}

Upvotes: 2

Related Questions