1

I have the following php code that displays csv data on the browser:

$file1 = file('SpreadsheetA.csv',FILE_IGNORE_NEW_LINES);
foreach($file1 as $val)
{
    echo $val;
}

the above outputs all the data in the csv file as a string:

Matter Number,Amount,Currency,Company Code100,2000,USD,310101,23000,EUR,110102,120,GBP,120103,10000,USD,310

if i want to capture the above as an array, this is what i do:

foreach($file1 as $val)
    {
        var_dump(array($val));
    }

and this is the output:

array(1) {
  [0]=>
  string(42) "Matter Number,Amount,Currency,Company Code"
}
array(1) {
  [0]=>
  string(16) "100,2000,USD,310"
}
array(1) {
  [0]=>
  string(17) "101,23000,EUR,110"
}
array(1) {
  [0]=>
  string(15) "102,120,GBP,120"
}
array(1) {
  [0]=>
  string(17) "103,10000,USD,310"
}

as shown, each string is captured as an array..my wish is to capture all strings under a single array as follows:

array(5) {
  [0]=>
  string(42) "Matter Number,Amount,Currency,Company Code"
  [1]=>
  string(16) "100,2000,USD,310"
  [2]=>
  string(17) "101,23000,EUR,110"
  [3]=>
  string(15) "102,120,GBP,120"
  [4]=>
  string(17) "103,10000,USD,310"
}

how would i accomplish the above(inside the foreach loop)??

1 Answer 1

1

you should loop your arrays into $file and fill another array with the string values

try this code:

$output = array();
foreach ($file1 as $val) {
    $output[] = $val[0];
}

var_dump(array($output));
Sign up to request clarification or add additional context in comments.

5 Comments

Invalid argument supplied for foreach() in C:\xampp\htdocs\masterclass\comparecsvfiles\try1.php on line 13 Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\masterclass\comparecsvfiles\try1.php on line 13 Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\masterclass\comparecsvfiles\try1.php on line 13 Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\masterclass\comparecsvfiles\try1.php on line 13 Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\masterclass\comparecsvfiles\try1.php array(1) { [0]=> array(0) { } }
displays:array(1) { [0]=> array(5) { [0]=> string(1) "M" [1]=> string(1) "1" [2]=> string(1) "1" [3]=> string(1) "1" [4]=> string(1) "1" } }
thanks ponciste.this works: $output = array(); foreach ($file1 as $val) { $output[] = $val; } var_dump(array($output));
i simply removed the [] in $val and left it as $output[] = $val;
ah ok, but it's weird since your output shows that var_dump(array($val)); are all arrays. By the way glad it working somehow :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.