Reputation: 29
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
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
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:
echo "my {$variable['foobar']}";
echo "my ".$variable['foobar'];
Upvotes: 1