Ask Your Question
2

Why do PHP variable variables display unexpected behavior when used with arrays?

asked 2021-09-26 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-01-22 06:00:00 +0000

pufferfish gravatar image

PHP variable variables have unexpected behavior when used with arrays because they are not intended to be used with arrays. Variable variables provide a way to dynamically create variable names by using the value of another variable as the name. However, when used with arrays, the variable name is interpreted as a string, which is not the intended behavior.

For example, consider the following code:

$my_array = [
    'foo' => 'hello',
    'bar' => 'world'
];

$var_name = 'my_array';

echo $$var_name['foo'];

The expected output would be "hello", since we are trying to access the "foo" element of the "myarray" array using a variable variable. However, the actual output is "m", because the expression $$varname['foo'] is interpreted as ${$varname}['foo']. Here, $varname is the string "my_array", and when we try to access the 'foo' element of this string, we get the first character ('m') instead.

To avoid this unexpected behavior, it is recommended to use standard array syntax instead of variable variables when working with arrays in PHP.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-26 11:00:00 +0000

Seen: 19 times

Last updated: Jan 22 '22