How can I output specific data from an associative array in PHP using foreach
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, let's say I wanted to output the name of the ALL products array like this:
Red shirt, Black shirt, Blue shirt
How can I achieve this with a foreach loop? I tried to output only a specific key from all arrays at the same time, but I cannot do it without outputting all keys.
You can also say that I just wanted to output the "price" of a specific array, eg $ products [103], how can I achieve this?
Thank!
source to share
you can use below code using foreach
foreach($products as $pro)
{
echo $pro['name'];
}
above code will only print name
the product array key
to get the price $product['103']
you can use as below code
foreach ($products as $key => $value)
{
if ($key == '103')
{
echo $pro['price'];
}
}
EDIT : get an array of names
$names = array();
foreach ($products as $pro)
{
$names[] = $pro['name'];
}
print_r($names);
he will return
Array ([0] => Red shirt [1] => Black shirt [2] => Blue shirt)
let me know if it helped you
source to share
Try the following code (This will cover all scenarios) :
function getMyArray($key, $arr = array()){
$result = array();
foreach($arr as $arrVal){
$result[] = $arrVal[$key];
}
return implode(", ", $result);
}
echo getMyArray('name', $products); // Red Shirt, Black Shirt, Blue Shirt
echo getMyArray('img', $products); //path1, path2, path3
echo getMyArray('price', $products); // 18, 20, 20
If you want to get a specific value:
echo $products[103]['price']; // 20
source to share