Katastrophenmagnet
Katastrophenmagnet

Reputation: 21

Actually easy PHP IF-statement on array

I'm working on a little thing for uni. However, the following is a small problem in the whole thing, which keeps me from progressing.

I read in a file containing the data on the names and want to sort it depending on the different details using if-statements so far. This is where the problem occurs:

for($i ;$i < count($file); $i++){
    if($i>0) {
        $data = explode(",", $file[$i]);
        echo $data[0] . $data[1] . $data[2] . $data[3] . $data[4];  //this works
        ?><br /><?php

        //The following one works too.
        if($data[0] == "Ann"){
            echo $data[0];
            ?><br /><br /><?php
        }

        // All these don't work
        if($data[3] == "californien") {
            echo 'Name: '. $data[0] . ', Occurences: '. $data[4];
            ?><br /><?php   
        }

        if($data[2] == "20-30"){
            echo $data[0];
            ?><br /><?php
        }

        if($data[1] == "w"){
            echo $data[0];
            ?><br /><?php
        }
    }
}

A sample from the csv file looks like this:

(Name, sex, year interval, state, occurences)

Mary, w, 10-20, californien, 88

Just using echo on some of the $data array elements works fine. Using the if-statement on the name ($data[0]) works, too. But if I wanna use any of the other parts like the interval, state sex, or occurrences it doesn't show anything at all.

I guess and hope it's just a small thing I didn't notice.

Anyone know what's wrong?

Upvotes: 1

Views: 73

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

Based on this input shown by you:-

(Name, sex, year interval, state, occurences)

Mary, w, 10-20, californien, 88

It seems you have white-spaces in your values.So you can resolve it like below:-

1.explode() with", "(comma with space) :-

$data = explode(", ", $file[$i]);

2.Or use trim() like below:-

if(trim($data[3]) == "californien") { // and so-on for others

A clean code need to be like below-

for($i ;$i < count($file); $i++){
    if($i>0) {
        $data = explode(", ", $file[$i]);

       //exploded with comma and spaces but confirm again through trim()

        if(trim($data[0]) == "Ann"){
            echo $data[0]."<br/><br/>";
        }

        if(trim($data[1]) == "w"){
            echo $data[0]."<br />";
        }

        if(trim($data[2]) == "20-30"){
            echo $data[0]."<br />";
        }

        if(trim($data[3]) == "californien") {
            echo 'Name: '. $data[0] . ', Occurences: '. $data[4]."<br />";
        }
    }
}

Upvotes: 1

Related Questions