0

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?

6
  • What are you going to use this function for? I don't think this is what you actually want to do. Commented Nov 13, 2017 at 15:48
  • Maybe, it's a good case for using a class with a static array? Commented Nov 13, 2017 at 16:00
  • every time when you can avoid using static properties. Commented Nov 13, 2017 at 16:01
  • @bassxzero I actually wanted to use $name_of_file as multidimensional array. With name and path of the file. Commented Nov 14, 2017 at 16:23
  • @splash58 mind suggesting me a good tutorial on classes? Cheers! Commented Nov 14, 2017 at 16:24

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

8 Comments

What if he doesn't want to update the array passed into the function? What if he is looking to update a static array inside the function?
then push and return.
And if he didn't actually want to return anything? Say he just wanted the array to be accessible, with the correct values, inside the function body?
My answer is point to the scope issue. If after this OP can not handle what he/she wants, I am so sorry. You have the possibilities to write your own answer, or you can ask him/her, what he/she really need.
@vaso123 "or you can ask him/her, what he/she really need." that's my point. I did ask him, and you posted your answer before he answered.
|

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.