简体   繁体   中英

problems with in_array ,returning false

I hope you can help me with this awkward issue. I am trying to get a certain value from all rows in a csv file,all works good until in_array().

CSV File looks like this:

Mach Vu,11-25-2012  21:32:39,row1
Mach Vu,11-25-2012  21:32:46,row2

I am trying to get last value from each row (ie 'row1','row2').

Here is my code:

$i = 1;

foreach($array2 as $key=>$value) {
    foreach($array2[$key] as $value2) {
        if($i % 3 == 0) {
           $array3[] = $value2;
        }
        $i++;
    }
}
print_r($array3);
echo "<br />";


if(in_array("row1", $array3)) {echo "yes";} else {echo "no";}

Array 3 is printing:

Array ( 
   [0] => row1
   [1] => row2
)

Thanks in advance for help ! All the best !

This may solve it for you, while also trimming down your code a bit and drastically improving performance.

My guess is that in_array isn't working due to extra whitespace, thus the addition of the trim()

$search = "row1";
$col = 2;
$found = false;

foreach ($array2 as $key => $value) {
    if (trim($value[$col]) == $search) {
        $found = true;
        break;
    }
}

print_r($array3);
print($found ? "yes" : "no");

How about something simpler?

$s = "Mach Vu,11-25-2012  21:32:39,row1";
$parsed_string = str_getcsv($s);
print $parsed_string[2];

This will print row1 . See the documentation for str_getcsv .

If you are reading a file, then try this (from the sample at the fgetcsv manual page ):

if (($handle = fopen("test.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $array3[] = $data[2];
   }
}
fclose($handle);

if (in_array("row1",$array3)) {
    print "yes";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM