views:

222

answers:

3

of all the languages i know im the weakest in php...

I have a script... that takes a csv file and does some stuff with it... fairly simple.

the issue i am having: in_array('username', $headers) ... returns null... while... print_r ($headers); shows username being the first entry in the csv.

thoughts? mistakes i may have made?

TIA

code here

/// Turn the string into an array
            $rows = explode("\n", $this->raw_data);

            /// First row includes headers
            $headers = $rows[0];
            $headers = explode($this->delimiter, $headers);

            /// Trim spaces from $headers
            $headers = array_map('trim', $headers);

            /// Check that there are no empty headers. This can happen if there are delimiters at the end of the file
            foreach($headers as $header){

                    if(!empty($header)){
                            $headers2[] = $header;
                    }
            }
            $headers = $headers2;

            if(! in_array('password', $headers)){
                    /// Add password column for generated passwords
                    $headers[] = 'password';
            }
            /// Add status column to the headers
            $headers[] = 'status';

            $this->headers = $headers;

            /// Check that at least username, name and email are provided in the headers
            if(!in_array('username', $headers) ||
               !in_array('name', $headers) ||
               !in_array('email', $headers)){

               echo "error\n";   
               return false;
            }
A: 

Check the first three functions in this list . Your problem can arise from several causes. Start by elimination of unnecessary parsing by using the built in CSV function.

Itay Moav
currently looking into this.
Kirby
A: 

I don't see code that sets $headers2 to be an array. Is the first assignment to that variable getting lost once the second assignment happens which turns it into an array?

Jason
i do the print_r ($headers); directly before the if statement that checks username... the output is such... Array ( [0] => username [1] => password [2] => email [3] => name )
Kirby
+2  A: 

You can use the built in str_getcsv() function. Try replacing the $headers variable assignment with

$headers = str_getcsv($rows[0], $this->delimiter);

Then find the value(column) you want and loop through the rest of the $rows using the same str_getcsv() function to get the matches you need.

You may want to use the file() function to grab the file in an array delimited by newlines to begin with, as well.

null