There is a code:

$arr= array( 2, 5, 9, 15, 0, 4); foreach ($arr as $key=>$value){ if ($value < 10 && $value>3) echo "\$arr[$key] = $value </br> "; } 

Conclusion:

 $arr[1] = 5 $arr[2] = 9 $arr[5] = 4; 

If in the line echo "\$arr[$key] = $value </br> " we remove \ output will be the following:

 5 = 5 9 = 9 4 = 4 

I just can't understand why not

 1 = 5 2 = 9 5 = 4 

Explain, please.

  • when you put a slash, a string is output because it escapes a dollar sign, otherwise php substitutes a variable in the string. If you want no substitution, either because of the question or in single quotes - splash58
  • Because you get without a slash reversal $arr[$key] , which is equivalent to $value . And with a slash, only the $key output, since the array itself is escaped ( \$ perceived as a simple symbol, not a variable call) and no search is performed on it. For the line you need, use echo "$key = $value </br> " - Alex Krass

3 answers 3

In the first case:

 echo "\$arr[$key] = $value </br> "; 

you escape the first $ character, so the line only produces two variables $key and $value , while $arr recognized as a string. From here such conclusion.

In the second case:

 echo "$arr[$key] = $value </br> "; 

$arr[$key] perceived as a variable, the value of which will be equal to $value . Hence the same values.

The following code will print the required result:

 echo "$key = $value </br> "; 

    To get this result as you want, output the data as follows:

     echo $key . ' = ' . $value . '<br>'; 

      If you use an expression inside a string, then frame it with parentheses: In this case, it is permissible to frame and just a variable.

      echo "$key = ${arr[$key]}"; Of course, in your case, on the right, it is permissible to use the value of $value . I just brought the syntax.