0
$myAry = array();

// I want to return the array's name.

// something like
echo $myAry.name;

// Should print "$myAry".

Thanks,

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
SpaceCorp
  • 21
  • 6

3 Answers3

0

But if you type $myAry you already know the name of the variable. What is it you are trying to achieve?

If you absolutely must know the identity of your variables...

function my_function ($my_array) {
    $caller_info = array_shift(debug_backtrace());
    $lines = file($caller_info['file']);
    $line = $lines[$caller_info['line'] - 1];
    if(preg_match('/my_function\\s*\\(\$(\\w+)/', $line, $matches)) {
        $name_of_my_array = $matches[1];
        echo $name_of_my_array;
    }

}

Is this what you want?

Vinay
  • 952
  • 2
  • 10
  • 27
  • Thank you, this is close, but it returns only the my_function's arg name(e.g. $my_array) every time, no matter what array is passed, and not what the arg is referring to. Example: if I use it like this my_function($new_name) It should return a string "$new_name" not "$my_array" as it does every time. – SpaceCorp Dec 28 '16 at 08:17
0

You can get argument name like this:

function get_function ($my_array) {
    $f = new ReflectionFunction($my_array);
    $result = array();
    foreach ($f->getParameters() as $param) {
        $result[] = $param->name;   
    }
    return $result;

}

function sayHello($helloWorlds){
    echo $helloWorld;
}

print_r(get_function('sayHello'));;


 //Output
 Array ( [0] => helloWorlds ) 
Query3j
  • 64
  • 1
  • 11
0

$array = array('name12'); $comma_separated = implode(",", $array);

echo $comma_separated; // name12

// Empty string when using an empty array:

var_dump(implode('hello', array())); // string(0) ""

Md.Jewel Mia
  • 3,345
  • 3
  • 19
  • 24