Array to string conversion and Only variables should be passed by reference

I am not experienced with php(i am new).

i am trying to use this code http://mach13.com/how-to-get-a-variable-name-as-a-string-in-php to find the name of a variable, but I keep getting:

Array to string conversion for the line :

$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));

and also i get "only variables should be passed by reference" when I use

var_name($a, get_defined_vars());

How can I make those messages disappear? Because the entire code is working(I get the desired output).

Here is the code

<?php
function var_name (&$iVar, &$aDefinedVars)
{
foreach ($aDefinedVars as $k=>$v)
    $aDefinedVars_0[$k] = $v;

$iVarSave = $iVar;
$iVar     =!$iVar;

$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
$iVar      = $iVarSave;

return $aDiffKeys[0];
}
$a=12;
echo var_name($a,get_defined_vars());
//ini_set('display_errors', '0');
?>

Answer #1:

The Array to String conversion notice started in PHP v5.4.0. Since array_diff_assoc() doesn't search recursively, it is notifying you that it found that one of the values in your array is also an array and it had to convert it to a string.

Here's an example on how to use array_diff_assoc() for a multi-dimensional array... http://nl3.php.net/manual/en/function.array-diff-assoc.php#73972

Or perhaps switching out array_diff_assoc() for array_diff_key() would work for your purpose if you are only comparing the keys?

Answered By: Scruffy Paws

Answer #2:

only variables should be passed by reference

You are passing the result of a function call as an argument. You aren't passing a variable.

$vars = get_defined_vars();
echo var_name($a,$vars);

Also, unless you're intentionally modifying one of the variables you shouldn't be passing it as a reference. That way any changes made are local to the function.

Answered By: Robert K
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles