In general, there is such a code:

$arr =["1","2","6"]; function test($a,$z) { $minus=$z[1]-$a; return $minus; } echo test(2,$arr); 

Is it possible to do not always point to $ arr? Like this:

 $arr =["1","2","6"]; function test($a) { $minus=$arr[1]-$a; return $minus; } echo test(2); 

Or something else you can?

    1 answer 1

    You can declare $ arr global as a function body:

     $arr = [1, 2, 6]; echo test(2); function test($a) { global $arr; return $arr[1] - $a; } 

    But this is not considered good practice.


    If you have PHP at least version 7, you can also declare a constant with an array structure (constants have a global scope) :

     const ARR = [1, 2, 6]; echo test(2); function test($a) { return ARR[1] - $a; } 

    If the version with constants is not suitable, you can form an array for transfer to the function by adding to the first element the value you need to work with in the function body. And in the body of the function, extract this first element from the array:

     $arr = [1, 2, 6]; array_unshift($arr, 2); echo test($arr); function test($arr) { $a = array_shift($arr); return $arr[1] - $a; } 

    Well, another option is to create another user-defined function that will return an array, and call this function in the body of the first function:

     echo test(2); function test($a) { return get_array()[1] - $a; } function get_array() { return [1, 2, 6]; } 
    • Unfortunately, PHP Version 5.6.8. And why is the first option considered not good? in terms of poor performance or vulnerability? - user286318 8:39 pm
    • @ user286318 in terms of supporting (debugging) the code. If the code is not large, and its development is not planned, and you are sure of this, then use global variables. Well, if the code is large, then you simply get tired of looking for a solution, in the case of some logical error, to look for the “that” variable. - Edward
    • @ user286318 I updated the answer with the account of your version of php. And you can still declare an array in the function body :) - Edward
    • the code is small, thanks a lot, I chose the option with global, but I also liked the last one, thanks a lot :) - user286318