Reputation: 963
I have the following line which reads a csv and turns each row into an Array
$reader = new CSV\CSVReader('somecsv.csv');
So if I then do
while ($row = $reader->getRow()) {
print "<pre>";
print_r($row);
print "</pre>";
}
It outputs data like so
Array
(
[Column1] => some
[Column2] => data
[Column3] => hi
[Column4] => wow
[Column5] => help
)
Array ...
Say I wanted to remove column1, inside the while loop I can place
unset($row['column1']);
And this will remove column1 from the output. However, if I place a function in my $reader class like so
public function unsetColumns($row)
{
unset($row['column1']);
}
And I change my while loop to the following
while ($row = $reader->getRow()) {
$reader->unsetColumns($row); //this does not work
unset($row['column1']); //this works
print "<pre>";
print_r($row);
print "</pre>";
}
Then the function call does not remove the column, but the unset does. I dont have both in there at the same time, just put them both there so you can see what works and what does not.
Why would this be?
Thanks
Upvotes: 3
Views: 49
Reputation: 18651
You can pass your array by reference read here more on Passing by Reference
public function unsetColumns(&$row)
{
unset($row['column1']);
}
while ($row = $reader->getRow()) {
$reader->unsetColumns($row); //this does not work
unset($row['column1']); //this works
print "<pre>";
print_r($row);
print "</pre>";
}
Upvotes: 1
Reputation: 29932
You can pass the current $row
by reference it to manipulate inside a function and also see those changes outside of that functions scope.
<?php
public function unsetColumns( &$row )
{
unset( $row['column1'] );
}
while( $row = $reader->getRow() ) {
$reader->unsetColumns( $row );
print "<pre>";
print_r($row);
print "</pre>";
}
The difference to your existing code is the additional ampersand in front of the arguments name: &$row
in the function declaration.
See: http://php.net/manual/en/language.references.pass.php
Upvotes: 1
Reputation: 23958
You are just passing $row
, it is getting deleted in function call also.
But, you are not returning it (neither you are passing reference to $row
).
Do two changes:
$row = $reader->unsetColumns($row);
And
public function unsetColumns($row)
{
unset($row['column1']);
return $row;
}
So, that your column deletion activity gets used.
Upvotes: 1