Skip to content
Advertisement

Accessing array value by direct passing value of another array in string

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?

Advertisement

Answer

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]]}";
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement