Someone please help me correcting the errors in this code This was the code where i am trying to find the names of the icecreams in stock
<?php
$flavors = array();
$flavors[]=array("name" => "CD" , "in_stock" => true);
$flavors[]=array("name" => "V" , "in_stock" => true);
$flavors[]=array("name" => "S" , "in_stock" => false);
foreach($flavors as $flavor => $value) {
if($flavor["in_stock"] == true) {
echo $flavor["name"] . "\n";
}
}
?>
Use
<?php
$flavors = array(
array("name" => "CD" , "in_stock" => true),
array("name" => "V" , "in_stock" => true),
array("name" => "S" , "in_stock" => false));
foreach($flavors as $flavor){
if ($flavor['in_stock'] == true) {
echo $flavor['name']."\n";
}
}
?>
instead
foreach($flavors as $flavor => value){
You are using multimentionals arrays, to use your aproach (=> value):
foreach ($flavors as $flavor => $value) {
if ($value['in_stock'] == true) {
echo $value['name']."\n";
}
}
You have flat non-associative array, that means you don't need to iterate using $key => $value
but just $item
.
So in you case the fix is that simple:
...
// foreach ($flavors as $flavor => $value) {
foreach ($flavors as $flavor) {
...
foreach() -
foreach
will additionally assign the current element's key to the$key
variable on each iteration
foreach (array_expression as $key => $value)
statement
Note: You can use any variable it's not necessary to use the variable with name $key
You are using the key for the condition $flavor["in_stock"]
and same for the $flavor["name"]
. You need to use $value
which holding the current iteration array
, correct use of foreach
for your code is
foreach($flavors as $flavor => $value) {
if($value["in_stock"] == true) {
echo $value["name"] . "\n";
}
}
Why iterate at all? One can just filter an array with a condition:
<?php
$flavors = [];
$flavors[] = ['name' => 'CD', 'in_stock' => true];
$flavors[] = ['name' => 'V', 'in_stock' => true];
$flavors[] = ['name' => 'S', 'in_stock' => false];
$inStock = array_filter($flavors, function (array $flavor) {
return $flavor['in_stock'];
});
print_r($inStock);
$inStockFlavors = array_column($inStock, 'name');
print_r($inStockFlavors);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.