Search code examples
phparraysarray-intersect

php array_intersect don't get the first value


Basically, I'm trying to import csv data to my database. Before insert the data to database I want to check whether database has that column (from csv headers) or not.

        // read csv from file ex: data.csv
        $reader = \League\Csv\Reader::createFromPath($file);            

        // get first row from csv as headers (email, first_name, last_name etc.)
        $headers = array_filter(array_map(function($value) { return strtolower(trim($value)); }, $reader->fetchOne()));

        // get fields from database (email, first_name, last_name, birthdate etc.)
        $fields = collect($this->fields)->map(function ($field) {
            return strtolower($field->tag);
        })->toArray();


        // want to check which fields has csv
        $availableFields = array_intersect($headers, $fields);

However when I run the code above, array_intersect not working properly.

The output is:

 $headers : Array ([0] => email [1] => first_name [2] => last_name ) 

 $fields : Array ( [0] => email [1] => first_name [2] => last_name     [3] => telephone     [4] => gender     [5] => birthdate     [6] => country  ) 

 $availableFields :Array ([1] => first_name [2] => last_name ) 

var_dump and result is:

$headers : array(3) {
  [0]=>
  string(8) "email"
  [1]=>
  string(10) "first_name"
  [2]=>
  string(9) "last_name"
}
$fields : array(9) {
  [0]=>
  string(5) "email"
  [1]=>
  string(10) "first_name"
  [2]=>
  string(9) "last_name"
  [3]=>
  string(9) "telephone"
  [4]=>
  string(6) "gender"
  [5]=>
  string(9) "birthdate"
  [6]=>
  string(7) "country"
}

Solution

  • The trim() function in php cuts off only 6 non-printable characters per default. I think that's your problem because there are more non-printable characters (list of characters).

    For example:

    <?php
    
    var_dump([trim("EMAIL\x1C")]);
    

    trim() allows you to specify a characters mask in the second parameter:

    <?php 
    
    trim($binary, "\x00..\x1F");
    

    Instead of using trim(), a regular expression gives more quarantee:

    <?php
    
    // preg_replace('/[\x00-\x1F\x7F]/u', '', $value)
    $headers = array_filter(array_map(function($value) { return strtolower(preg_replace('/[\x00-\x1F\x7F]/u', '', $value)); }, $reader->fetchOne()));