Raunaq Sahni
Raunaq Sahni

Reputation: 29

Why do I need to wrap array variable with curly brackets in PHP sometimes

I am trying to create two related drop down menus, where decision on one affects the options on the other. I ran into this interesting thing where in my second foreach loop, where I pass $subcategory['id'], it shows me an error. If wrap {$subcategory['id']} in curly braces it works fine. I want to understand why this is happening.

<?php
$categories = [
  [
    'id' => 1, 'name' => 'Furniture', 'subcategories' => [
      ['id' => 1, 'name' => 'Beds'],
      ['id' => 2, 'name' => 'Benches'],
      ['id' => 3, 'name' => 'Cabinets'],
      ['id' => 4, 'name' => 'Chairs & Stools'],
      ['id' => 5, 'name' => 'Consoles & Desks'],
      ['id' => 6, 'name' => 'Sofas'],
      ['id' => 7, 'name' => 'Tables']
    ]
  ],
  [
    'id' => 2, 'name' => 'Lighting', 'subcategories' => [
      ['id' => 1, 'name' => 'Ceiling'],
      ['id' => 2, 'name' => 'Floor'],
      ['id' => 3, 'name' => 'Table'],
      ['id' => 4, 'name' => 'Wall']
    ]
  ],
  [
    'id' => 3, 'name' => 'Accessories', 'subcategories' => [
      ['id' => 1, 'name' => 'Mirrors'],
      ['id' => 2, 'name' => 'Outdoor & Patio'],
      ['id' => 3, 'name' => 'Pillows'],
      ['id' => 4, 'name' => 'Rugs'],
      ['id' => 5, 'name' => 'Wall Decor & Art'],
    ]
  ]
];

  $category_id = isset($_GET['category_id']) ? (int) $_GET['category_id'] : 0;

  foreach($categories as $category) {
    if($category['id'] == $category_id) {

      $subcategories =   $category['subcategories'];
foreach($subcategories as $subcategory){
  echo "<option value=\" {$subcategory['id']} \">";
  echo $subcategory['name'];
  echo "</option>";
}


    }
  }

?>

Upvotes: 0

Views: 392

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

You can interpolate values from arrays using simple syntax (no curly braces) if you don't quote the array key. You can see an example of this in the simple syntax section of the PHP string documentation.

echo "<option value=\"$subcategory[id]\">";

If you want to do anything more complicated than that, then you'll need to use complex syntax (curly braces).

Upvotes: 1

Anthony Aslangul
Anthony Aslangul

Reputation: 3847

It's because you are echoing an array entry inside a double quoted string.

echo "hello $another_variable"; //works if $another_variable can be converted to string
echo "hello $arr['something']"; //error anyway
echo "hello {$arr['something']}"; //works

Basically, if you need to do something more complex than just using a simple $variable, you have to either use:

  • The curly brackets syntax: echo "my {$variable['foobar']}";
  • Concatenation: echo "my ".$variable['foobar'];

Upvotes: 1

Related Questions