Pure Rhymer Organization Pure Rhymer Organization - 3 months ago 9
PHP Question

Whats the use of & in function parameters?

I found this in tutorial on how to import excel in PHP but I cant find it in internet whats the use of

&
in the function parameter?

Here is the code:

<?php
$data = array(
array("First Name" => "Nitya", "Last Name" => "Maity", "Email" => "nityamaity87@gmail.com", "Message" => "Test message by Nitya"),
);

function filterData(&$str) <--------------THIS LINE--------<
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}

// file name for download
$fileName = "codexworld_export_data" . date('Ymd') . ".xls";

// headers for download
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");

$flag = false;
foreach($data as $row) {
if(!$flag) {
// display column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
// filter data
array_walk($row, 'filterData');
echo implode("\t", array_values($row)) . "\n";
}

exit;
?>


edited

Does this line the same as
function filterData($params)
?

Answer

With that "&" you are passing the variable by reference and not by value

http://php.net/manual/en/language.references.pass.php

No it is not the same

<?php

function filterData(&$str) 
{
    $str .= "new";
}
$a = "Hello";
filterData($a);
echo $a;
?>

In this case the system prints Hellonew

When you use the "&" every change you make to the variable still valid even outside the function. But please have a look on the link because my explanation is short and not complete (should be good for you to understand the difference between reference and value even for performance e security problems)