0

I tried to access the array value by passing the value of another array element in the string.

Here is the example.

$arr = array("asif", "ali");
$arr2 = array("asif" => 3, "ali" => 5);

echo "value of data $arr2[$arr[0]]";

It is giving me the error as

syntax error, unexpected '[', expecting ']'

I tried to access the value out of the string like the following.

$arr = array("asif", "ali");
$arr2 = array("asif" => 3, "ali" => 5);

echo $arr2[$arr[0]];

It is working fine.

Then I tried to use just a single array in the string and pass the other array's element value by variable.

$arr = array("asif", "ali");
$arr2 = array("asif" => 3, "ali" => 5);

$name = $arr[0];

echo "value of data $arr2[$name]";

It is also working fine.

Is there something wrong in the syntax?

1
  • 1
    it's not a bug, you just need wrap it in curly braces if you want it interpolated in the quoted string Commented Dec 3, 2020 at 9:49

1 Answer 1

3

You need complex syntax to expand arrays like that.

Change this:

echo "value of data $arr2[$arr[0]]";

To this:

echo "value of data {$arr2[$arr[0]]}";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.