Array Help

Hi, I am stuck!

Here is what I am trying to do. I need to import 2 csv files as arrays and compare the data and generate a 3rd csv file. CSV 1 is an inventory with 2 columns serial number, and computer name. CSV 2 has only 1 column with computer names. I would like to generate a new csv 3 file based on the computer names in csv 2 that contains the matching serial number from csv1, if no match is found for that computer name then leave the serial number blank or say not found.

Can anyone help?

Please supply some test data.

csv1.csv example would be the following

csv2.csv example would be

Result I am looking for would be to create the following csv3.

doesnt exist, desktop15,

I assume I need to use fgetcsv to create the arrays.

This won’t work, if you have multiple computers that doesn’t have a serial number then they will overwrite eachother as array keys are unique.

$array[] = ‘foo’;
$array[] = ‘bar’;
$array[‘unique’] = ‘this’;
$array[‘unique’] = ‘is’;
$array[‘unique’] = ‘a’;
$array[‘unique’] = ‘test’;

echo ‘


As you can see from the output “this”, “is”, “a” is not in the array. The same would happen to your computers.

I am looking to create a new csv file with the matching serial numbers. Here is what I have right now, not sure how to write this.


<?php $lwsdata = array(); //$lwslookup = array(); $file = fopen('csv1.csv', 'r'); $file2 = fopen('csv2.csv', 'r'); $addFile = fopen('csv3.csv', "w"); while (($data = fgetcsv($file)) !== FALSE){ $lwsdata[$data[0]] = $data[0]; $lwsdata[$data[1]] = $data[1]; } while (($data2 = fgetcsv($file2))!== FALSE){ if (array_key_exists($data2[0],$lwsdata)){ // echo "$data2[0] exists"; //Create new csv with the matching serial number for each computer name in csv2 from csv1 fputcsv($addFile,$lwsdata); } else { //otherwise just add a line that has the original name with no matching serial number fputcsv($addFile,$data2); } } ?>


This should work


function parseListToArray ($filename) {
$result = array();
$file = fopen($filename, ‘r’);
while (($line = fgetcsv($file)) !== FALSE) {
// Condition to check if the line is with and without serial
if (empty($line[1])) {
$result[] = $line[0];
} else {
$result[$line[0]] = $line[1];


return $result;

// Parse the files into arrays
$csv1 = parseListToArray(‘csv1.csv’);
$csv2 = parseListToArray(‘csv2.csv’);

// Iterate through csv2 to find all items missing from csv1, add them to a temporary string
$missing = ‘’;
foreach ($csv2 as $product) {
if (!in_array($product, $csv1)) {
// product is not in array, create a string to insert into the list
$missing .= ‘,’ . $product . PHP_EOL;


  • Write to file

// Get original file data
$data = file_get_contents(‘csv1.csv’);

if (!empty($missing)) {
// Append missing products
$data .= PHP_EOL . $missing;

// Write to file
file_put_contents(‘csv3.csv’, $data);[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service