Kevin G
Kevin G

Reputation: 63

If Statement shows only once in foreach loop

i have a question regarding a foreach loop in PHP. For some reason i seem to only get the last line echo'ed back this way and i am lost in where this problem lies. Whenever i check $onderdeeltje[1] and $selectedmodel in an echo inside the foreach loop and outside the IF statement it pastes them all out perfectly without any problems. It also shows that they are equal and the same and should react on the IF statement.. As soon as i compare the two inside IF statement it shows me only the last one. Whenever i remove the checkbox echo and replace it with anything such as echo "test"; it also shows me test only once. Could anybody shed some light on this? I have multiple (2 + this one) foreach loops like this in the same page that work perfectly but only this one seems to bug.

echo "<form method='post' action='formpie.php'>";

$onderdelen = file("onderdelen.txt");

foreach ($onderdelen as $onderdeel) 
{
    $onderdeeltje = explode(",", $onderdeel);

    if ($onderdeeltje[1] == $selectedmodel)
    {
        echo "<input type='checkbox' name='check_list[]' value='$onderdeeltje[0]'>$onderdeeltje[0]<br>";
    }
}

echo "</form>";

$selectedmodel will be: iPhone 3G and the text list is this:

Reparatie touchscreen €41.50,iPhone 3G
Reparatie Wi-Fi-antenne €50.00,iPhone 3G
Reparatie trilmodule €40.00,iPhone 3G
Reparatie sim slot €70.50,iPhone 3G
Reparatie oorluidspreker €46.00,iPhone 3G

It only shows: Reparatie oorluidspreker €46.00 as a checkbox.

Please help me out! :) Thanks in advance!

-------------------------------------------------------------

How to solve:

It seems that there can be hidden spaces in the ouput that are not visible if these are pasted per line with things like <br> or in my case a list of repeated form checkbox values.

To fix this you simply have to trim the value before or inside the IF equal statement like so:

foreach ($onderdelen as $onderdeel) 
{
    $onderdeeltje = explode(",", $onderdeel);

    if (trim($onderdeeltje[1]) == $selectedmodel)
    {
        echo "<input type='checkbox' name='check_list[]' value='$onderdeeltje[0]'>$onderdeeltje[0]<br>";
    }
}

Solved thanks to support from ZombieSpy.

Upvotes: 1

Views: 1954

Answers (1)

ZombieSpy
ZombieSpy

Reputation: 1376

As Marc B said, you might have the newline stuff, so use str_replace

echo "<form method='post' action='formpie.php'>";

$onderdelen = file("onderdelen.txt");

foreach ($onderdelen as $onderdeel) 
{
    $onderdeeltje = explode(",", $onderdeel);

    if (str_replace ("\n", "", $onderdeeltje[1]) == $selectedmodel)
    {
        echo "<input type='checkbox' name='check_list[]' value='$onderdeeltje[0]'>$onderdeeltje[0]<br>";
    }
}

echo "</form>";

Upvotes: 0

Related Questions