Geevz
Geevz

Reputation: 13

If condition always returning true

I am reading a text file line by line and each line has comma separated values. example

Name,Phone,URL,notavailable

The reading is fine and the script returns the lines correctly. The last value has "available" or "notavailable".

I am exploding a line like this

$sections = explode(",", $line);

and it returns

    Array
    (
        [0] => Name
        [1] => Phone
        [2] => URL
        [3] => notavailable

    )

I can get values using

$sections[0], $sections[1] etc.

And they display just fine. But the problem occurs when I try to compare the last value.

$check = $sections[3];
if($check=="notavailable")
{Do something }
else {Do something else}

But the if statement always returns false. I could not figure that out. Tried so many time. It will be so much helpful somebody can point out the error in my script.

Thanks in advance.

Upvotes: 1

Views: 571

Answers (3)

Prakash GPz
Prakash GPz

Reputation: 1523

try using

 if(preg_match_all('/notavailable/i',$section[3]))
 {
    // Not Available
 }
 else
 {
     // Available
 }

Upvotes: 0

Epsil0neR
Epsil0neR

Reputation: 1704

$a == $b Equal TRUE if $a is equal to $b after type juggling. $a === $b Identical TRUE if $a is equal to $b, and they are of the same type.

When you read file, you also read spaces, so you need to trim them.

So you should use:

if(trim($section[3]) === "notavailable"){
    //Do something
} else {
    //Do something else
}

Upvotes: 1

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137487

You need to do a little debugging. Throw in a line like

$check = $sections[3];
echo "check = '$check'";    // Debug print

If you print it out in quotes like that, you'll probably see there are leading/trailing spaces. If that is the case, a simple call to trim() will take care of it.

Upvotes: 3

Related Questions