0

I have the requirement to run a function that takes an array and then effectively prints the content of that array out. Very simple, however I would want to include the name of the array that was passed to that function.

I've read about using "hack" methods such as debug_backtrace to find the calling file and line number and then parsing that line for the name of the function, which is certainly an option (albeit convoluted). An alternative would be to call the function with a string, that string being the name of the array and then within the function, declare a global :

function showArray($array){
    global $$array;
    echo $array . ' contains the following:<pre>';
    print_r($$array);
    echo '</pre>';
}

// set up a test array for demo purposes
$testArray = [];
for($i=0; $i<10; $i++){
    $testArray[$i] = md5(uniqid());
}

// call the function with string, not the array itself
showArray('testArray');

This certainly shows the response that I would like:

testArray contains the following:
Array
(
    [0] => 18c19a1daf7b62e2d064697850dd1bf2
    [1] => 3fc8981f8b4e3a72fc48419389e246ae
    ..
    [8] => 47d28676305ffaef7c7e10e7950f5bb3
    [9] => db20f5b27f9917ebee7ab149df759387
)

But do wonder if there's something hidden in PHP that I'm unaware of, that precludes me from using this approach? Unless it's absolutely 100% required (which is may be in this case), AFAIK it's "poor" practice to use globals ...

bnoeafk
  • 489
  • 4
  • 16
  • Possible duplicate of [How to get a variable name as a string in PHP?](https://stackoverflow.com/questions/255312/how-to-get-a-variable-name-as-a-string-in-php) – splash58 Nov 22 '17 at 21:09
  • I don't believe it is a duplicate. Arrays passed to functions are done so using their content. The only name the function knows about is that with which it was defined by, there's no (immediate) reference to the variable name outside of the functions scope. – bnoeafk Nov 22 '17 at 23:52

0 Answers0