Reputation: 783
I'm trying to make a function which accepts a value and echo them in the end.
Here's an example:
function number_of_files ($name) {
$name_of_files = array($name);
var_dump ($name_of_files);
}
And I'm using this function as
number_of_files("file.png");
number_of_files("audio.mp3");
I'm expecting the following output:
Array (
[0] => file.png
[1] => audio.mp3
)
Any suggestions why is it not working?
Upvotes: 0
Views: 120
Reputation: 12391
Nope. You are overwrite your $name_of_files
every time. That variable in the functions scope.
Use this:
function number_of_files ($name, &$name_of_files) {
array_push($name_of_files, $name);
}
$name_of_files = number_of_files('file.mpg', $name_of_files);
$name_of_files = number_of_files('audio.mp3', $name_of_files);
var_dump ($name_of_files);
Now you are using your array as a reference.
EDIT:
If you do not want to overwrite your original array, you can return:
function number_of_files ($name, $name_of_files) {
array_push($name_of_files, $name);
return $name_of_files;
}
But let's note, in the second case I did not used the &
sign before the $name_of_files
function argument. That is the reference marker.
You can read it here: http://php.net/manual/en/language.references.pass.php
Upvotes: 3