My associative array:
$products = array();
$products[101] = array(
"name" => "Red Shirt",
"img" => "img/shirts/shirt-101.jpg",
"price" => 18
);
$products[102] = array(
"name" => "Black Shirt",
"img" => "img/shirts/shirt-102.jpg",
"price" => 20
);
$products[103] = array(
"name" => "Blue Shirt",
"img" => "img/shirts/shirt-103.jpg",
"price" => 20
);
So lets say I wanted to output the name of ALL products array like so:
Red Shirt, Black Shirt, Blue Shirt
how can I achieve that with a foreach loop? I have tried to output only a specific key from all arrays at once but I cannot seem to do it without outputting all the keys.
Also lets say I wanted to just output the "price" of a certain array like $products[103] how can I achieve that?
Thank you!
you can use below code, with using foreach
foreach($products as $pro)
{
echo $pro['name'];
}
above code will print only name
key of the product array
to get price of $product['103']
you can use like below code
foreach ($products as $key => $value)
{
if ($key == '103')
{
echo $pro['price'];
}
}
EDIT : to get array of names
$names = array();
foreach ($products as $pro)
{
$names[] = $pro['name'];
}
print_r($names);
it will return
Array ( [0] => Red Shirt [1] => Black Shirt [2] => Blue Shirt )
let me know if this helped you
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments